xlutils仅适用于xls,不适用于xlsx? [英] xlutils only works on xls, not xlsx?
问题描述
我有一个现有的Excel工作簿,Workbook_A
.我正在创建一个相同的工作簿Workbook_B
,然后在新工作簿的某些单元格中插入一些值.
I have an existing Excel workbook, Workbook_A
. I'm creating an identical workbook, Workbook_B
, and then insert a few values into some of the cells in the new workbook.
我正在做的事情的简化版本:
A simplified version of what I'm doing:
from xlrd import open_workbook
from xlutils.copy import copy
rb = open_workbook(Workbook_A)
wb = copy(rb)
s = wb.get_sheet(0)
s.write(row, col, value)
wb.save(Workbook_B)
Workbook_A
在这里可以是xlsx
文件,但是我必须将其另存为xls
文件Workbook_B.xls
.否则文件将损坏,无法打开.
Workbook_A
can be an xlsx
file here, but I must save it as an xls
file, Workbook_B.xls
. Otherwise the file becomes corrupt and impossible to open.
是否可以解决此问题?我可以将xlutils
与xlsx
一起使用,还是该模块与该Excel格式不兼容?
Is there a way to fix this? Can I use xlutils
with xlsx
, or isn't the module compatible with that Excel-format?
Is openpyxl
the solution?
I'm not the first one to encounter this problem, but I can't find a fix.
推荐答案
由于xlutils
依赖xlrd
(用于读取文件)和xlwt
(用于写入文件),因此xlutils
实际上是使用xlwt
.
As xlutils
relies on xlrd
(to read files) and xlwt
(to write files), thus, the save
function of xlutils
actually using xlwt
.
.xlsx
是与.xls
相比较新且完全不同的文件格式(基本上是压缩的xml文件).虽然xlrd
已升级为读取.xlsx
文件,但xlwt
未升级为 write 这样的文件(
.xlsx
is a newer and completely different file format (basically zipped xml files) from .xls
. While xlrd
has been upgraded to read .xlsx
files , xlwt
wasn't upgraded to write such files (does xlwt support xlsx Format).
由于xlwt
仅写入较旧的Excel(.xls
)文件, .xlsx扩展名不会改变任何事情.基础格式仍然是.xls
(由于它依赖扩展名而不是内容来决定如何打开文件,因此被MS Excel视为已损坏)
Since xlwt
only writes older Excel (.xls
) files, passing a .xlsx extension doesn't change a thing. The underlying format is still .xls
(and is seen as corrupt by MS Excel because it relies on the extension, not on contents, to decide how to open the file)
因此,可以使用openpyxl
做您想做的事情(完全删除xlutils
,xlrd
,xlwt
,因为您不关心旧版.xls
格式),或者另存为临时xlrd
读回底页并写回openpyxl
.
So, either use openpyxl
to do what you want (drop xlutils
, xlrd
, xlwt
entirely since you don't care about legacy .xls
format), or save as a temporary .xls
file using your current process, then read it back sheet by using xlrd
and write back to openpyxl
.
根据当前代码的复杂性,您可以选择完全重写还是包含更多程序包的肮脏解决方法(但要避免重写当前代码)
Depending on the complexity of your current code, you may choose between a full rewrite or a dirty workaround involving much more packages (but avoiding to rewrite the current code)
这篇关于xlutils仅适用于xls,不适用于xlsx?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!