这里我们需要使用到两个package:
xlrd 和 xlutils
但是在使用 xlutils 的时候遇到了不少坑!
比如找不到模块:
module 'xlutils' has no attribute 'copy'
解决方案:把 xlutils 内的模块都写进 init.py 文件
from .compat import *
from .copy import *
from .display import *
from .filter import *
from .margins import *
from .save import *
from .styles import *
from .view import *
程序代码:
import xlrd
import xlutils
# 打开一个 excel 文件
old_excel = xlrd.open_workbook('./test.xls')
workbook_all = xlutils.copy(old_excel)
# 获取 sheet 对象
sheet = workbook_all.get_sheet(0)
# 修改数据
sheet.write(1, 1, 'modified!')
# 添加 sheet 页
workbook_all.add_sheet('sheet2',cell_overwrite_ok=True)
# 这里如果已经有了 sheet2,那会报错:Exception: duplicate worksheet name 'sheet2'
# 保存同名文件,达到覆盖修改的目的,其中未被修改的内容保持不变
workbook_all.save('./test.xls')
这里发现:使用这种方法保存为 “.xlsx” 后缀的文件,会无法打开!需要改成老的后缀 “.xls” 才能打开!