【问题标题】:Easy way to fill in an Excel file with Python用 Python 填写 Excel 文件的简单方法
【发布时间】:2013-08-24 21:31:40
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 如果保存为 Excel 97 - 为什么是test.xlsx?如果您可以确定它是什么版本(以及您希望输出的 Excel 版本),这将很有用
  • @Jon Clements 抱歉,您是对的,已使用 excel for mac 2011 版本 14.0.1 保存为 xlsx - 刚刚更新了 Q
  • 您看过 Python 的 xlwt、xlrd 和 xlutils 模块了吗? (python-excel.org)
  • @josh,很好的建议,现在研究一下

标签: python linux macos excel


【解决方案1】:

我建议使用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

【讨论】:

    猜你喜欢
    • 2014-03-21
    • 2017-07-09
    • 2016-06-14
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多