python完整复制excel模板_Python Excel模板读取和重写,维护公式和格式

1586010002-jmsa.png

I've run the gamut and can't seem to find what I'm looking for. All threads I found here end up in dead ends for me. xlrd, xlwt, and xlutils almost do what I need, but… The basic idea is that I need to use Python to write simple data (strings) to a particular sheet of an Excel template and write out that template to a new .xls file.

Reading in the template, copying it to a new workbook object, writing in the new values, and writing out the new .xls file is no problem. However, I cannot find a Python Excel module that maintains both formulae and formatting.

`

our = 'template.xls'

# open up read-only template with formatting maintained

rb = open_workbook(our,formatting_info=True)

r_sheet = rb.sheet_by_index(4)

# copy this to a new workbook object

wb = copy(rb)

# 5th sheet (index = 4) is where we need to drop the data we have

w_sheet = wb.get_sheet(4)

# populate with new data!

for row_index in range(0, r_sheet.nrows):

w_sheet.write(row_index, 1, "some string that is our data")

# write it!

wb.save('new.xls')

`

When reading in the template, the formatting is maintained (slightly altered for some colors; meh!), but the formulae are not, so "new.xls" is has blanks all over the place where formulae once stood.

Any idea how to maintain both formatting and formulae?

Note, I'm locked in to Python 2.7.

解决方案

You can use openpyxl for this - it only supports xlsx (and the related formats), and not xls (the old Excel format).

This package does preserve formulas when you open/save the Excel sheet. Also it does preserve formatting, but there are some minor issues with it. Images from the original Excel file are not preserved, though.

Other cool features include support for conditional formatting, charts, sparklines, and many more.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值