首页 文章

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

提问于
浏览
1

有一个真实的用例 . 希望能够使用Pandas进行一些数据聚合和操作,设想的工作流程如下:

  • 在Excel文件中查找指定的单元格

  • 到达单元块的边界(由空列/行定义的边界)

  • 将单元块读入Pandas DataFrame

  • 用熊猫做事

  • 将生成的DataFrame写回同一个Excel文件,再写入另一个命名单元格定义的位置

  • 保留Excel文件的图表和公式

2 回答

  • 1

    我认为你需要使用像DataNitro这样的额外资源 . https://datanitro.com

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

  • 1

    由于该问题已被低估,因此其他人不太可能提供答案 . 只是在这里发布我的实现:

    我使用了名为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
    

相关问题