我们假设我有一个名为 test.xlsx 的excel文件,这是一个包含三张工作簿的工作簿,其中sheet1称为 hello1 ,sheet2两个称为 hello2 ,而sheet3被称为再见。
现在,我想读取该文件,然后重新编写相同的文件,但只更改名为hello2的工作表(第B列,第11行)中的值,以及(第D列,第14行)表单名为bye。我想要给出的值分别是'test'(一个字符串)和135(即,在表单hello2中写入测试,在单独表格中为14)。
你可能想知道为什么我会问这样一个奇怪的问题,但基本上我希望获得以下一些技能/知识:
注意:作为参考,我可以在redhat服务器中使用任何版本的python,excel文件是用我的mac生成的,使用excel for mac 2011保存为xlsx格式。版本14.0.1,然后我复制了excel文件到redhat服务器。
答案 0 :(得分:6)
看起来你所做的事情看起来并不依赖于单元格中已有的值,因此除了打开书本外,你根本不需要使用xlrd
。 xlrd
,xlwt
和xlutils
的工作方式是使用xlrd
来读取工作簿,然后使用xlutils
制作可写副本。所以你的代码的快速模型看起来像:
import xlrd, xlwt
from xlutils.copy import copy
rb = xlrd.open_workbook("Path/To/Doc", formatting_info=True) #Make Readable Copy
wb = copy(rb) #Make Writeable Copy
ws1 = wb.get_sheet(1) #Get sheet 1 in writeable copy
ws1.write(1, 11, 'test') #Write 'test' to cell (1, 11)
ws2 = wb.get_sheet(2) #Get sheet 2 in writeable copy
ws2.write(3, 14, '135') #Write '135' to cell (3, 14)
wb.save("New/File/Path") #Save the newly written copy. Enter the same as the old path to write over