我对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`