Python 操作excel:修改excel文件中的数据(附 xlutils.copy 无法使用的解决方案)

这里我们需要使用到两个package:
xlrdxlutils

但是在使用 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” 才能打开!

发布了44 篇原创文章 · 获赞 0 · 访问量 1724

猜你喜欢

转载自blog.csdn.net/qq_42067550/article/details/105466112