python - 使用 Python 填写 Excel 文件的简单方法

标签 python linux macos excel

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

现在,我想读取文件,然后重写同一个文件,但只更改名为 hello2 的工作表(B 列,第 11 行)和(D 列,第 14 行)中的值工作表命名为再见。我想给那里的值分别是“测试”(一个字符串)和 135(即,在工作表 hello2 中写测试,在工作表 bye 中写 14)。

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

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

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

最佳答案

我建议使用 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 (B, 11)

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

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

关于python - 使用 Python 填写 Excel 文件的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18423298/

相关文章:

linux - 防止在 bash 中意外编辑历史记录

macos - Mac 上不显示 Outlook 插件

ios - 如何使用 Foundation 框架在 Swift 中创建和运行线程?

python - Ubuntu python-dateutil 安装/升级问题。 dateutil.zoneinfo.gettz 返回 NoneType

python - 使用 Python 在 Matplotlib Basemap 中将自然地球形状绘制为多边形

linux - wordpress vuejs样板 Bootstrap 安装错误

linux - 在 Bash 中运行时按下按键时更改脚本输出

python - 使用 "del np.dtype"后,重新导入 numpy 是否应该修复此问题?

python - Pandas 没有在 y 轴上显示 timedelta 所需的结果

objective-c - 有没有办法在浏览器上将 Cocoa 应用程序作为工作表打开?