openpyxl 与 Pandas、NumPy

openpyxl可以与 Pandas 和 NumPy 库一起使用。

NumPy 支持

openpyxl 内置支持 NumPy 的 float、integer 和 boolean 数据类型。 使用 Pandas 的时间戳类型支持 DateTimes。

使用 Pandas 的 DataFrame 数据类型

openpyxl.utils.dataframe.dataframe_to_rows() 方法提供了一种使用Pandas Dataframe 的简单用法:

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 的转换,但以上方法为客户端代码提供了更多的灵活性,包括直接将数据帧流传输到文件的能力。
以下操作将 DataFrame 类型数据转换为突出显示标题和索引的工作表:

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")

若只转换数据,可以使用只写模式将 DataFrame 类型数据转换为突出显示标题和索引的工作表:

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")

以上代码将与标准工作簿一起使用。

将工作表转换为 DataFrame

使用 values 属性可以将工作表转换为 DataFrame 类型数据,如果工作表没有标题或索引,这将非常容易:

df = DataFrame(ws.values)

如果工作表包含标题或索引(例如 Pandas 创建的标题或索引),将工作表转换为 DataFrame 类型数据需要这样做:

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)

badboy
7 声望4 粉丝