openpyxl能够与流行的库熊猫Pandas和NumPy一起使用。
NumPy库支持¶
openpyxl内置了对NumPy类型float、integer和boolean的支持。日期时间类型支持Pandas的时间戳。
使用Pandas数据帧¶
openpyxl.utils.dataframe.dataframe_to_rows方法提供了使用Pandas数据帧的简单方法:
1 from openpyxl.utils.dataframe import dataframe_to_rows
2 wb = Workbook()
3 ws = wb.active
4
5 for r in dataframe_to_rows(df, index=True, header=True):
6 ws.append(r)
Pandas本身支持到Excel的转换,这为客户端代码提供了额外的灵活性,例如能够将数据帧传输到文件。
要将数据帧转换为突出显示标题和索引的工作表,请执行以下操作:
1 wb = Workbook()
2 ws = wb.active
3
4 for r in dataframe_to_rows(df, index=True, header=True):
5 ws.append(r)
6
7 for cell in ws['A'] + ws[1]:
8 cell.style = 'Pandas'
9
10 wb.save("pandas_openpyxl.xlsx")
或者,如果您只想转换数据,可以使用只写模式:
1 from openpyxl.cell.cell import WriteOnlyCell
2 wb = Workbook(write_only=True)
3 ws = wb.create_sheet()
4
5 cell = WriteOnlyCell(ws)
6 cell.style = 'Pandas'
7
8 def format_first_row(row, cell):
9
10 for c in row:
11 cell.value = c
12 yield cell
13
14 rows = dataframe_to_rows(df)
15 first_row = format_first_row(next(rows), cell)
16 ws.append(first_row)
17
18 for row in rows:
19 row = list(row)
20 cell.value = row[0]
21 row[0] = cell
22 ws.append(row)
23
24 wb.save("openpyxl_stream.xlsx")
这段代码在标准工作簿中也同样适用。
将工作表转换为数据帧¶
要将工作表转换为数据帧,可以使用values属性。如果工作表没有标题或索引,转换操作很容易:
1 df = DataFrame(ws.values)
如果工作表中确实有标题或索引(如Pandas创建的标题或索引),则需要稍多的工作:
1 from itertools import islice
2 data = ws.values
3 cols = next(data)[1:]
4 data = list(data)
5 idx = [r[0] for r in data]
6 data = (islice(r, 1, None) for r in data)
7 df = DataFrame(data, index=idx, columns=cols)
水平有限,如果有朋友发现文中许多翻译不当的地方,请随时指正。翻译不易,也请大家多多点赞!