用Python填充Excel文件的简单方法

2024-09-26 17:58:04 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个名为test.xlsx的excel文件,它是一个有三张工作表的工作簿,其中sheet1被称为hello1,sheet2 2被称为hello2,sheet3被称为bye

现在,我想读取该文件,然后重新写入相同的文件,但只更改名为hello2的工作表的(B列,第11行)和名为bye的工作表的(d列,第14行)中的值。我要给出的值分别是“test”(字符串)和135(即,在sheet hello2中编写test,在sheet bye中编写14)。

你可能想知道我为什么要问这么奇怪的问题,但基本上我希望获得以下一些技能/知识:

  • 使用python读取工作簿和excel文件的特定工作表
  • 能够使用python在给定位置写入excel工作表

注意:作为参考,我可以在redhat服务器中使用任何版本的python,excel文件是用我的mac生成的,用excelformac2011保存为xlsx格式。版本14.0.1,然后我将excel文件复制到redhat服务器。


Tags: 文件字符串test版本服务器xlsxexcelsheet
1条回答
网友
1楼 · 发布于 2024-09-26 17:58:04

我建议使用xlwtxlrdxlutils模块(您可以在这里找到:python-excel.org)。

使用xlrdxlwtxlutils,可以使用xlrd读取工作簿,然后使用xlutils生成可写副本。因为您所做的工作不依赖于单元格中已有的值,所以除了打开书本之外,您根本不需要使用xlrd

代码的快速模型如下所示:

import xlrd, xlwt
from xlutils.copy import copy

read_book = xlrd.open_workbook("Path/To/Doc", formatting_info=True) #Make Readable Copy
write_book = copy(read_book) #Make Writeable Copy

write_sheet1 = write_book.get_sheet(1) #Get sheet 1 in writeable copy
write_sheet1.write(1, 11, 'test') #Write 'test' to cell (1, 11)

write_sheet2 = write_book.get_sheet(2) #Get sheet 2 in writeable copy
write_sheet2.write(3, 14, '135') #Write '135' to cell (3, 14)

write_book.save("New/File/Path") #Save the newly written copy. Enter the same as the old path to write over

相关问题 更多 >

    热门问题