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')