python openpyxl operating Excel spreadsheet

Original: It's not allowed to reprint, attribution required

It is going to be divided into two parts:
The first part is: Operation Excel spreadsheet
second part: Operation Excel chart
is now published as the first part


In a recent project to extract the Android log frame rate, after calculation, a need exists for the table, so the private study next openpyxl, documented record.

A, openpyxl installation

1.1 python does not own openpyxl, you need to install.

pip install openpyxl

1.2 After successful installation import project

import openpyxl

Excel 1.3 operating three elements:

  1. Workbook:
    Excel document is a workbook
  2. Worksheet:
    data workbook PivotTable. Such as "sheet", "sheet1"
  3. Cells:
    PivotTable basic unit for storing data. The "A1", "C4"

Second, create a workbook and worksheet with openpyxl module

2.1 Create a workbook:

workbook = openpyxl.Workbook(write_only=False)

note:

write_only=True代表只读,是不能执行创建和写入操作的。
write_only=False代表可读可写

2.2 Creating a worksheet:

workbook.create_sheet(title="sheet_name", index=0)

note:

title="sheet_name":工作表名称
index=0:工作表在工作簿中的展示位置

Such as:

workbook.create_sheet("sheet_name_0",0)
workbook.create_sheet("sheet_name_1",1)
workbook.create_sheet("sheet_name_2",2)
workbook.create_sheet("sheet_name_3",1) # 注意sheet_name_3的位置

Obtain a work sheet in the workbook you just created

workbook.get_sheet_names()

Output:

['sheet_name_0', 'sheet_name_3', 'sheet_name_1', 'sheet_name_2', 'Sheet']

Why more than the last 'Sheet'?
The reason:
When the workbook is blank, the first created worksheets, create a default number of worksheets.
In the present embodiment, when creating sheet_name_0, Sheet out also be created by default.
How many default number of worksheets and the operating system.

2.3 Obtaining the active worksheet and view the worksheet name

sheet = workbook.get_active_sheet() #获取的是上次保存退出后,活动的工作表
print(sheet.title)

Export

'sheet_name_0'

2.4 Select the worksheet and rename sheets

sheet = workbook.get_sheet_by_name('Sheet') # 创建时默认创建的一个工作表
print("活动表名:",sheet.title)
sheet.title = 'sheet_name_4' #为sheet.title属性赋值,即可实现重命名
print("重命名后的活动表名:",sheet.title)

Output:

活动表名:Sheet
重命名后的活动表名:sheet_name_4

2.5 a write data to the active sheet, used for reading and writing below.

datas = [
            ['Draw', 'Prepare', 'Process', 'Execute'],
            ['1.77', '0.31', '1.34', '1.05'],
            ['2.95', '0.28', '1.25', '0.92'],
            ['3.04', '0.28', '1.24', '1.05'],
            ['3.25', '0.32', '1.43', '1.06'],
            ['2.09', '0.28', '1.38', '1.09'],
            ['1.73', '0.29', '1.35', '0.89'],
            ['2.90', '0.31', '1.49', '1.03'],
            ['3.30', '0.37', '1.63', '0.97'],
            ['2.29', '0.36', '1.73', '1.12']
        ]
        
for row in datas:
    sheet.append(row)

2.6 complete code section:

workbook = openpyxl.Workbook(write_only=False)  #创建工作簿
workbook.create_sheet("sheet_name_0",0)         #创建工作表
workbook.create_sheet("sheet_name_1",1)         #创建工作表
workbook.create_sheet("sheet_name_2",2)         #创建工作表
workbook.create_sheet("sheet_name_3",1)         # 注意sheet_name_3的位置

sheet = workbook.get_sheet_by_name('Sheet')     # 选定工作表为活动工作表
sheet.title = 'sheet_name_4'                    # 重命名工作表 

datas = [
            ['Draw', 'Prepare', 'Process', 'Execute'], #创建一匹数据
            ['1.77', '0.31', '1.34', '1.05'],
            ['2.95', '0.28', '1.25', '0.92'],
            ['3.04', '0.28', '1.24', '1.05'],
            ['3.25', '0.32', '1.43', '1.06'],
            ['2.09', '0.28', '1.38', '1.09'],
            ['1.73', '0.29', '1.35', '0.89'],
            ['2.90', '0.31', '1.49', '1.03'],
            ['3.30', '0.37', '1.63', '0.97'],
            ['2.29', '0.36', '1.73', '1.12']
        ]
        
for row in datas:
    sheet.append(row)
    
workbook.save("test_excel.xlsx")                # 保存工作簿,一定要保存,否则不会写入文件

Third, the data read module openpyxl Microsoft Excel worksheet

3.1 Delete Sheet

workbook = openpyxl.load_workbook("test_excel.xlsx", read_only=False)
sheet_names = workbook.get_sheet_names()
print(sheet_names)

Output:

['sheet_name_0', 'sheet_name_3', 'sheet_name_1', 'sheet_name_2', 'sheet_name_4']

To delete the sheet is sheet_name_0, sheet_name_1, sheet_name_2, retention sheet_name_3 and sheet_name_4

workbook.remove_sheet(workbook.get_sheet_by_name("sheet_name_0"))
workbook.remove_sheet(workbook.get_sheet_by_name("sheet_name_1"))
workbook.remove_sheet(workbook.get_sheet_by_name("sheet_name_2"))

Check Sheet again

sheet_names = workbook.get_sheet_names()
print(sheet_names)

Output:

['sheet_name_3', 'sheet_name_4']

Now test_excel.xlsx workbook worksheet has changed, if you want to output to a file, you need to save the changes.

workbook.save("test_excel.xlsx")

The change has been updated to the workbook.

Note:
remove_sheet () accepts a Worksheet is a type parameter, so use workbook.get_sheet_by_name ( "sheet_name_0") to get a Worksheet object.

3.2 reading cell
reading cell A1

sheet = workbook.get_sheet_by_name("sheet_name_4")
a1 = sheet['A1']    
# sheet['A1'] 和 sheet.cell(row=1, column=1) 等价
print(type(a1))     # 查看单元格类型
print("value = ", a1.value, " , row = ", a1.row, " ,column = ", a1.column, " , coordinate = ", a1.coordinate)

Output:

<class 'openpyxl.cell.cell.Cell'>
value =  Draw  , row =  1  ,column =  1  , coordinate =  A1

Reading a cell 3.3

sheet = workbook.get_sheet_by_name("sheet_name_4")
A1_D2 = sheet['A1':'D2']
print(A1_D2)

Output:

((<Cell 'sheet_name_4'.A1>, <Cell 'sheet_name_4'.B1>, <Cell 'sheet_name_4'.C1>, <Cell 'sheet_name_4'.D1>), (<Cell 'sheet_name_4'.A2>, <Cell 'sheet_name_4'.B2>, <Cell 'sheet_name_4'.C2>, <Cell 'sheet_name_4'.D2>))

Analysis output

(   # 元组
    # 第一行 数据结果 A1到D1 四列 
    (<Cell 'sheet_name_4'.A1>, <Cell 'sheet_name_4'.B1>, <Cell 'sheet_name_4'.C1>, <Cell 'sheet_name_4'.D1>),
    # 第二行 数据结果 A2到D2 四列
    (<Cell 'sheet_name_4'.A2>, <Cell 'sheet_name_4'.B2>, <Cell 'sheet_name_4'.C2>, <Cell 'sheet_name_4'.D2>)
)

The value of print A1_D2

for row in A1_D2:       # 读取第一行 元组
    for column in row:  # 读取列 元组 内 4 列数据即A1到D4
        print("value = ", column.value, " , row = ", column.row, " ,column = ", column.column, " , coordinate = ", column.coordinate)
    print("-----END ROW-----")

3.4 modify the cell data
using the D10 cell A2 to the data are respectively +1

workbook = openpyxl.load_workbook("test_excel.xlsx", read_only=False)
sheet = workbook.get_sheet_by_name("sheet_name_4")
A2_D10 = sheet['A2':'D10']
for row in A2_D10:
    for column in row:
        column.value = float(column.value)+1    # 修改Cell.value属性值即可达到修改单元格的目的。

workbook.save("test_excel.xlsx")                # 将修改更新保存到工作簿

3.5 Operating Summary:

  1. Import module openpyxl
  2. Call openpyxl.Workbook () or openpyxl.load_workbook () function, to obtain a Workbook object
  3. Call get_active_sheet () or get_sheet_by_names () function, to obtain the active table Worksheet Object
  4. Use Sheet [Index] or sheet.cell (row = row, column = column) to give the object Cell
  5. Cell object to read or write the value argument

Guess you like

Origin blog.csdn.net/weixin_34290000/article/details/90931314