gpt4 book ai didi

python - 使用 xlrd 和 xlwt 编辑现有的 excel 工作簿和工作表

转载 作者:IT老高 更新时间:2023-10-28 22:11:06 25 4
gpt4 key购买 nike

documentation对于 xlrdxlwt 我学到了以下内容:

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

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

open_workbook 只是 xlrd 模块的一部分,而不是 xlwt

有什么想法吗?

编辑1:在 Olivers 建议后,我查看了 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')

最佳答案

正如我在 op 的编辑中所写,要编辑现有的 excel 文档,您必须使用 xlutils 模块(感谢 Oliver)

以下是正确的做法:

#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”,然后保存文档。

关于python - 使用 xlrd 和 xlwt 编辑现有的 excel 工作簿和工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26957831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com