這裏我們需要使用到兩個package:
xlrd 和 xlutils
但是在使用 xlutils 的時候遇到了不少坑!
比如找不到模塊:
module 'xlutils' has no attribute 'copy'
看了下安裝的 package 文件,發現 __init__.py
是空的!
於是又去查閱 github 上的信息:
xlutils 在 github 上的鏈接
發現 __init__.py
文件確實是空的。
照理來說不應該呀!我想是不是被人篡改了?而這個 xlutils 包實際上用的人並不多,所以也一直沒人發現。
最早很多撰寫的 xlutils 使用教程並沒有出現這個問題,說明當時__init__.py
文件肯定不是空的!
解決方案:把 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” 才能打開!