编辑已有excel文件

python可以使用xlrd读excel,使用xlwt写excel,但是如果要把数据写入已存在的excel,需要另外一个库xlutils配合使用.

大概思路:

1、用xlrd.open_workbook打开已有的xsl文件。注意添加参数formatting_info=True,得以保存之前数据的格式;
2、然后用 from xlutils.copy import copy ,通过copy 从打开的xlrd的Book变量中,拷贝出一份,成为新的xlwt的Workbook变量;
3、然后对于xlwt的Workbook变量,就是正常的,通过get_sheet去获得对应的sheet,拿到sheet变量后,就可以往sheet中,写入新的数据;
4、写完新数据后,最终save保存。

源码例子:

import xlrd
import os
from xlutils.copy import copy
from xlwt import Style
 
def writeExcel(row, col, str, styl=Style.default_style):
    rb = xlrd.open_workbook(file, formatting_info=True)
    wb = copy(rb)
    ws = wb.get_sheet(0)
    ws.write(row, col, str, styl)
    wb.save(file)
 
style = xlwt.easyxf('font:height 240, color-index red, bold on;align: wrap on, vert centre, horiz center');
writeExcel(1, 1, 'hello world', style)   

如果需要excel原格式,需要加参数 formatting_info=True。

如果需要加excel样式,传入样式字符串给xlwt.easyxf即可。

合并单元格:ws.write_merge(top_row, bottom_row, left_column, right_column, string) 。
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值