Python桌面软件自动化,5分钟掌握openpyxl“俏皮”功能
需要将各种数据导入Excel?想要合并多个Excel?目前Python处理Excel文件的库有很多,openpyxl是功能和性能较好的库之一。接下来,我将向您介绍Excel的各种功能。 打开Excel文件
创建新的Excel文件
>>> from openpyxl import Workbook
>>> wb = Workbook()
打开现有的Excel文件
>>> from openpyxl import load_workbook
>>> wb2 = load_workbook('test.xlsx')
打开大文件时,请根据需要使用只读或只写模式,以减少内存消耗。
wb = load_workbook(filename='large_file.xlsx', read_only=True)
wb = Workbook(write_only=True)
获取并创建工作表 获取当前工作表:
>>> ws = wb.active
创建新工作表:
>>> ws1 = wb.create_sheet("Mysheet") # insert at the end (default)
# or
>>> ws2 = wb.create_sheet("Mysheet", 0) # insert at first position
# or
>>> ws3 = wb.create_sheet("Mysheet", -1) # insert at the penultimate position
使用任务名称获取工作表:
>>> ws3 = wb["New Title"]
获取所有任务的名称:
>>> ws3 = wb["New Title"]
print(wb.sheetnames) 另存为单元格位置使用的传输:‿直接读取为功能键: 指定值至单元格: 多个单元格可以使用切片访问单元格字段: 使用数字格式: 除左上角之外的所有单元格工作表中的角将被删除: 您可以指定单独的行、列或平均值: 您可以使用 ets.iWork_rows。 () 迭代行的方法: >>> ws = wb.active 或
['sheet2','new title','sheet1']
使用使用粘贴所有任务:>> in wb:
... print(sheet.title)保存 >>> c = ws['A4']
>>> ws['A4'] = 4
>>> c.value = 'hello, world'
>>> cell_range = ws['A1':'C2']
>>> # set date using a Python datetime
>>> ws['A1'] = datetime.datetime(2010, 7, 21)
>>>
>>> ws['A1'].number_format
'yyyy-mm-dd h:mm:ss'
>>> # set date using a Python datetime
>>> ws['A1'] = datetime.datetime(2010, 7, 21)
>>>
>>> ws['A1'].number_format
'yyyy-mm-dd h:mm:ss'
>>> # set date using a Python datetime
>>> ws['A1'] = datetime.datetime(2010, 7, 21)
>>>
>>> ws['A1'].number_format
'yyyy-mm-dd h:mm:ss'
>>> # set date using a Python datetime
>>> ws['A1'] = datetime.datetime(2010, 7, 21)
>>>
>>> ws['A1'].number_format
'yyyy-mm-dd h:mm:ss'
>>> # set date using a Python datetime
>>> ws['A1'] = datetime.datetime(2010, 7, 21)
>>>
>>> ws['A1'].number_format
'yyyy-mm-dd h:mm:ss'
行、列 >>> ws.merge_cells('A2:D2')
>>> ws.unmerge_cells('A2:D2')
>>>
>>> # or equivalently
>>> ws.merge_cells(start_row=2, start_column=1, end_row=4, end_column=4)
>>> ws.unmerge_cells(start_row=2, start_column=1, end_row=4, end_column=4)
>>> colC = ws['C']
>>> col_range = ws['C:D']
>>> row10 = ws[10]
>>> row_range = ws[5:10]
>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
... for cell in row:
... print(cell)
<Cell Sheet1.A1>
<Cell Sheet1.B1>
<Cell Sheet1.C1>
<Cell Sheet1.A2>
<Cell Sheet1.B2>
<Cell Sheet1.C2>
Worksheet.iter_cols()
将迭代所有列:♷ 您可以使用 Worksheet.rows
属性:
>>> ws['C9'] = 'hello world' >>> ws.线)
((, , ),
(, , ),
(, , ),
(, , ),
(、、)、
(、、)、
(、、)、
(、、)、
(、, ))Sheet.columns: ♾ 元组(ws.columns)
((,
,
,
),
(,
,
,
,
,
,
,
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。