简单用法¶
写入工作表¶
>>> from openpyxl import Workbook
>>> from openpyxl.utils import get_column_letter
>>>
>>> wb = Workbook()
>>>
>>> dest_filename = 'empty_book.xlsx'
>>>
>>> ws1 = wb.active
>>> ws1.title = "range names"
>>>
>>> for row in range(1, 40):
... ws1.append(range(600))
>>>
>>> ws2 = wb.create_sheet(title="Pi")
>>>
>>> ws2['F5'] = 3.14
>>>
>>> ws3 = wb.create_sheet(title="Data")
>>> for row in range(10, 20):
... for col in range(27, 54):
... _ = ws3.cell(column=col, row=row, value="{0}".format(get_column_letter(col)))
>>> print(ws3['AA10'].value)
AA
>>> wb.save(filename = dest_filename)
读取已有的工作表¶
>>> from openpyxl import load_workbook
>>> wb = load_workbook(filename = 'empty_book.xlsx')
>>> sheet_ranges = wb['range names']
>>> print(sheet_ranges['D18'].value)
3
备注
在使用 load_workbook
函数时有几个可供选择。
data_only
控制带有公式的单元格是否具有公式(默认值)或 Excel 上次读取工作表时存储的值。keep_vba
控制是否保留任何 Visual Basic 元素(默认)。如果它们被保存,它们仍然不能被编辑。
警告
用 openpyxl 打开文件并进行保存会导致图片和图表的丢失,因为 openpyxl 无法读取 Excel 文件所有可能的项。
使用数字格式¶
>>> import datetime
>>> from openpyxl import Workbook
>>> wb = Workbook()
>>> ws = wb.active
>>> # set date using a Python datetime
>>> ws['A1'] = datetime.datetime(2010, 7, 21)
>>>
>>> ws['A1'].number_format
'yyyy-mm-dd h:mm:ss'
使用公式¶
>>> from openpyxl import Workbook
>>> wb = Workbook()
>>> ws = wb.active
>>> # add a simple formula
>>> ws["A1"] = "=SUM(1, 1)"
>>> wb.save("formula.xlsx")
警告
您必须为函数使用英文名称,并且函数参数必须用逗号分隔,而不能使用其他标点符号,例如分号。
openpyxl 不会检查公式但可以检查公式的名称:
>>> from openpyxl.utils import FORMULAE
>>> "HEX2DEC" in FORMULAE
True
如果你正在尝试使用未知的公式,可能是因为这公式未被包含在最初的规范中。这样的公式只有以 _xlfn.
为前缀才能起作用。
合并 / 拆分单元格¶
当您合并单元格时,除了左上角的单元格外,所有的单元格都将从工作表中 删除。为了携带合并单元格的边界信息,合并单元格的边界单元格被创建为 MergeCells,其值总是为 None。有关合并单元格的格式化信息,请参阅 Styling Merged Cells 。
>>> from openpyxl.workbook import Workbook
>>>
>>> wb = Workbook()
>>> ws = wb.active
>>>
>>> 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)
插入图片¶
>>> from openpyxl import Workbook
>>> from openpyxl.drawing.image import Image
>>>
>>> wb = Workbook()
>>> ws = wb.active
>>> ws['A1'] = 'You should see three logos below'
>>> # create an image
>>> img = Image('logo.png')
>>> # add to worksheet and anchor next to cells
>>> ws.add_image(img, 'A1')
>>> wb.save('logo.xlsx')
折叠(大纲)¶
>>> import openpyxl
>>> wb = openpyxl.Workbook()
>>> ws = wb.create_sheet()
>>> ws.column_dimensions.group('A','D', hidden=True)
>>> ws.row_dimensions.group(1,10, hidden=True)
>>> wb.save('group.xlsx')