使用 xlrd 和 xlwt 编辑现有 Excel 工作簿和工作表

2024-03-04

In the 文档 http://www.simplistix.co.uk/presentations/python-excel.pdf for xlrd and xlwt我学到了以下内容:

如何阅读现有的工作簿/工作表:

from xlrd import open_workbook
wb = open_workbook("ex.xls")
s = wb.sheet_by_index(0)
print s.cell(0,0).value
#Prints contents of cell at location a1 in the first sheet in the document called ex.xls

如何创建新的工作簿/工作表:

from xlwt import Workbook
wb = Workbook()
Sheet1 = wb.add_sheet('Sheet1')
Sheet1.write(0,0,'Hello')
wb.save('ex.xls')
#Creates a document called ex.xls with a worksheet called "Sheet1" and writes "Hello" to the cell located at a1

我现在想做的是在现有工作簿中打开现有工作表并写入该工作表。

我尝试过类似的事情:

from xlwt import open_workbook
wb = open_workbook("ex.xls")
s = wb.sheet_by_index(0)
print s.cell(0,0).value

but open_workbook只是其中的一部分xlrd模块,不是xlwt.

有任何想法吗?

编辑1: 在奥利弗的建议之后我调查了xlutils并尝试了以下方法:

from xlrd import open_workbook
from xlwt import Workbook
from xlutils.copy import copy

wb = open_workbook("names.xls")
s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')

然而,这给了我以下错误消息:

File "C:\Python27\lib\site-packages\xlrd\book.py", line 655, in get_sheet
raise XLRDError("Can't load sheets after releasing resources.")
xlrd.biffh.XLRDError: Can't load sheets after releasing resources.

编辑2: 该错误消息是由于使用不当造成的get_sheet功能。 终于知道怎么用了:

from xlrd import open_workbook
from xlwt import Workbook
from xlutils.copy import copy

rb = open_workbook("names.xls")
wb = copy(rb)

s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')

正如我在操作编辑中所写,要编辑现有的 Excel 文档,您必须使用xlutils模块(感谢奥利弗)

这是正确的方法:

#xlrd, xlutils and xlwt modules need to be installed.  
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy

rb = open_workbook("names.xls")
wb = copy(rb)

s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')

这会将“names.xls”第一页中 a1 处的单元格内容替换为文本“a1”,然后保存文档。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 xlrd 和 xlwt 编辑现有 Excel 工作簿和工作表 的相关文章

随机推荐