编写工作簿¶
>>> 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
注解
有几个标志可用于加载工作簿。
-
data_only
标志用于指定带公式的单元格内容是存储的公式(默认值)或者上次Excel读取时的计算值。 -
keep-vba
标志是否保留vba脚本(默认设置)。如果保留它们,它们仍然不可编辑。
警告
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值。
>>> 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')
水平有限,如果有朋友发现文中许多翻译不当的地方,请随时指正。
翻译不易,也请大家多多点赞!