openpyxl能够与流行的Pandas和NumPy一起使用。
NumPy库支持¶
openpyxl内置了对NumPy类型float、integer和boolean的支持。日期时间类型支持Pandas的时间戳。
使用Pandas数据帧¶
openpyxl.utils.dataframe.dataframe_to_rows
方法提供了使用Pandas数据帧的简单方法:
from openpyxl.utils.dataframe import dataframe_to_rows
wb = Workbook()
ws = wb.active
for r in dataframe_to_rows(df, index=True, header=True):
ws.append(r)
Pandas本身支持到Excel的转换,这为客户端代码提供了额外的灵活性,例如能够将数据帧传输到文件。
要将数据帧转换为突出显示标题和索引的工作表,请执行以下操作:
wb = Workbook()
ws = wb.active
for r in dataframe_to_rows(df, index=True, header=True):
ws.append(r)
for cell in ws['A'] + ws[1]:
cell.style = 'Pandas'
wb.save("pandas_openpyxl.xlsx")
或者,如果您只想转换数据,可以使用只写模式:
from openpyxl.cell.cell import WriteOnlyCell
wb = Workbook(write_only=True)
ws = wb.create_sheet()
cell = WriteOnlyCell(ws)
cell.style = 'Pandas'
def format_first_row(row, cell):
for c in row:
cell.value = c
yield cell
rows = dataframe_to_rows(df)
first_row = format_first_row(next(rows), cell)
ws.append(first_row)
for row in rows:
row = list(row)
cell.value = row[0]
row[0] = cell
ws.append(row)
wb.save("openpyxl_stream.xlsx")
这段代码在标准工作簿中也同样适用。
将工作表转换为数据帧¶
要将工作表转换为数据帧,可以使用values
属性。如果工作表没有标题或索引,转换操作很容易:
df = DataFrame(ws.values)
如果工作表中确实有标题或索引(如Pandas创建的标题或索引),则需要稍多的工作:
from itertools import islice
data = ws.values
cols = next(data)[1:]
data = list(data)
idx = [r[0] for r in data]
data = (islice(r, 1, None) for r in data)
df = DataFrame(data, index=idx, columns=cols)
网友评论