python办公自动化用openpyxlpandasnumpy_openpyxl3.0官方文档(6)—— 和Pandas、NumPy库一起使用...

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)

水平有限,如果有朋友发现文中许多翻译不当的地方,请随时指正。翻译不易,也请大家多多点赞!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值