[Study Notes] Python Office Automation - Task 02 Operation Excel

There are no exercises in the learning process this time, mainly to be familiar with using openpyxl to operate excel tables.

Using openpyxl to operate excel mainly includes three levels of operation objects
1. An excel file => workbook
2. A page of worksheet => sheet
3. A cell => cell

1. Excel file operation (whole file)
#引入openpyxl相关操作库
from openpyxl import load_workbook
from openpyxl import Workbook

#新建excel表
workbook_new = Workbook()
#打开excel表
workbook = load_workbook('./test.xlsx')
#保存excel表
workbook_new.save('new.xlsx')
workbook.save('./test1.xlsx')
Two, sheet worksheet operation
#引入openpyxl相关操作库
from openpyxl import load_workbook

#打开excel表
workbook = load_workbook('./test.xlsx')
#所有工作表名称
sheetNames = workbook.sheetnames
#获取当前活动的sheet
sheet_active = workbook.active
#获取name=work的工作表
sheet = workbook['work']
#创建新的sheet
sheet_new = workbook.create_sheet("newsheet") 
#复制一个sheet对象
sheet_copy = workbook.copy_worksheet(sheet)
#获取当前sheet名称
print(sheet.title)
#获取当前sheet最大行和最大列
print(sheet.max_row)
print(sheet.max_column)
#获取当前sheet所有行和列(元组形式不方便使用,加list后每行为一个元组,所有行的元组组成一个列表)
print(list(sheet.rows)) 
print(list(sheet.columns))  
#删除sheet
workbook.remove(sheet_copy) 
Three, cell cell operation
#获取某个单元格  三种方式
print(sheet['A1']) 
print(sheet.cell(3,2)) 
print(list(sheet.rows)[2][1])

#获取多个单元格
a2_b3 = sheet['a2':'b3']
b = sheet['b'] #返回b列的所有cell对象
row1 = sheet['1'] #返回第1行的所有cell
a_e = ws['a:e'] #a-e列的cell对象

#返回列数、行数、值
cell=sheet['A1']
print(cell.column)
print(cell.row)
print(cell.value)
#单元格样式
print(cell.font)

#修改单元格值
sheet['a2'] = 222 
sheet['a2'] = 'aaa'
sheet['b2'] = '=SUM(A1:A17)' #使用公式
cell.value = 222

Guess you like

Origin blog.csdn.net/qq_41794040/article/details/118035245