与熊猫和麻木的人一起工作

OpenPYXL能够与流行的库一起工作 PandasNumPy

麻木支撑

OpenPYXL内置了对numpy类型float、integer和boolean的支持。使用熊猫的时间戳类型支持日期时间。

使用熊猫数据帧

这个 openpyxl.utils.dataframe.dataframe_to_rows() 函数提供了使用熊猫数据帧的简单方法:

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)

如果工作表确实有标题或索引,例如由熊猫创建的标题或索引,则需要做更多的工作:

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)