Pandas 可以读取和修改单个 Excel 文件工作表(选项卡)而不修改文件的其余部分吗?

2024-03-19

许多电子表格具有用于读写 Excel 文件的 Python 工具无法忠实再现的公式和格式。这意味着我想要以编程方式创建的任何文件都必须是我基本上从头开始创建的文件,然后其他 Excel 文件(具有上述复杂性)必须引用该文件(这会产生各种其他依赖性问题)。

我对 Excel 文件“选项卡”的理解是它们实际上只是 XML 文件的集合。那么,是否可以使用 pandas(或底层读/写引擎之一,例如 xlsxwriter 或 openpyxl 来修改其中一个选项卡,而使其他选项卡(其中有更多邪恶的东西)保持不变?

编辑:我将尝试用一个例子进一步阐明这个问题。

  • Excel Sheet test.xlsx 有四个选项卡(又名工作表):Sheet1、Sheet2、Sheet3、Sheet4
  • 我使用 pandas.read_excel() 将 Sheet3 读入 DataFrame(我们称之为 df)
  • Sheet1和Sheet2包含openpyxl和xlrd都无法成功解析的公式、图表和各种格式,Sheet4包含其他数据。我根本不想碰那些标签。
  • Sheet2 实际上有一些对 Sheet3 上单元格的引用
  • 我对 df 进行了一些编辑,现在想将其写回到sheet3,保持其他工作表不变(并且工作簿中其他工作表对它的引用保持不变)

我可以这样做吗?如果可以,怎么做?


我对excel和python(特别是pandas)之间的交互有一个类似的问题,我被提到了这个问题。

感谢 stackoverflow 社区的一些指点,我找到了一个名为xlwings http://docs.xlwings.org/quickstart.html#interact-with-excel-from-python这似乎涵盖了 HaPsantran 所需的许多功能。

使用OP的例子:

使用现有的 Excel 文件,您可以通过在 Excel 中命名要导入到 pandas 的数据块(Sheet3)中放置一个锚点,然后执行以下操作:

# opened an existing excel file

wb = Workbook(Existing_file)

# Find in the excel file a named cell and reach the boundary of the cell block (boundary defined by empty column / row) and read the cell 

df = Range(Anchor).table.value

# import pandas and manipulate the data block
df = pd.DataFrame(df) # into Pandas DataFrame
df['sum'] = df.sum(axis= 1)

# write back to Sheet3
Range(Anchor).value = df.values

测试发现此实现没有调整 excel 文件中的现有公式

如果这可以解决您的问题以及是否有什么我可以帮助的,请告诉我。

非常感谢 xlwings 的开发者,他们让这一切成为可能。


以下是在 @jamzsabb 提出进一步问题后对我之前答案的更新,并反映 xlwings 更新到 >= 0.9.0 后更改的 API。

import xlwings as xw
import pandas as pd
target_df = xw.Range('A7').options(pd.DataFrame, expand='table').value # only do this if the 'A7' cell (the cell within area of interest) is in active worksheet
#otherwise do:
#sht = xw.Book(r'path to your xlxs file\name_of_file.xlsx`).sheets['name of sheet']
#target_df = sht.Range('A7').options(pd.DataFrame, expand='table').value # you can also change 'A7' to any name that you've given to a cell like 'interest_table`
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pandas 可以读取和修改单个 Excel 文件工作表(选项卡)而不修改文件的其余部分吗? 的相关文章

随机推荐