读取/写入Excel文件中的特定位置

有一个真正的用例。 希望能够用pandas做一些数据聚合和操作,设想工作stream程如下:

  1. 在Excel文件中查找一个已命名的单元格
  2. 到达单元块的边界(由空列/行定义的边界)
  3. 将单元格块读入Pandas DataFrame
  4. 做pandas的东西
  5. 将生成的DataFrame写回到同一个Excel文件,到另一个命名的单元格定义的位置
  6. 保留Excel文件的图表和公式

我想你需要使用像DataNitro这样的附加资源。 https://datanitro.com

或者使用less量的VBA启动进程,将命名的范围转储到csv,从命令提示符运行python并传递csv文件,使用VBA打开它并将结果处理到工作表中。

由于这个问题已经被低估了,所以别人不可能提供答案。 只是在这里发布我的实现:

我使用了名为xlwings的优秀python包,如果您拥有python的conda发行版,可以很容易地安装它。

wb = Workbook(Existing_file) # opened an existing excel file df = Range('tb_st').table.value # 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 block import pandas as pd df = pd.DataFrame(df) # into Pandas DataFrame df['sum'] = df.sum(axis= 1) # do stuff with Pandas Range('cp_tb').value = df.values # Write the resulting DataFrame back to the same Excel file, to a location defined by another named cell # tested that this implementation didn't temper any existing formula in the excel file