python - 使用 Pandas 修改 Excel 文件,布局更改最少

标签 python excel pandas openpyxl xlsxwriter

我已经阅读了Can Pandas read and modify a single Excel file worksheet (tab) without modifying the rest of the file?但在这里我的问题是特定于后面提到的布局。
如何使用 Pandas 打开 Excel 文件,进行一些修改,然后将其保存回来:

  • (1) 不删除存在 Filter在第一行
    enter image description here
  • (2)不修改Excel中显示的列的“显示列宽”
  • (3) 不删除某些单元格上可能存在的公式

  • ?
    这是我尝试过的,这是一个简短的示例(实际上我使用 Pandas 进行了更多处理):
    import pandas as pd
    
    df = pd.read_excel('in.xlsx')
    df['AB'] = df['A'].astype(str) + ' ' + df['B'].astype(str)  # create a new column from 2 others
    del df['Date']                                              # delete columns
    del df['Time']
    df.to_excel('out.xlsx', index=False)
    
    使用此代码,Filter删除第一行的宽度并将显示的列宽设置为默认值,这不是很方便(因为我们必须手动为所有列设置正确的宽度)。

    最佳答案

    如果您使用的是安装了 Excel 的机器,那么我强烈建议您使用灵活的 xlwings API。这回答了你所有的问题。
    假设我有一个名为 demo.xlxs 的 Excel 文件。在与我的程序相同的目录中。
    enter image description hereapp.py

    import xlwings as xw # pip install xlwings
    import pandas as pd
    
    wb = xw.Book('demo.xlsx')
    
    enter image description here
    这将创建一个启动 xl 工作簿实例并打开您的 Excel 编辑器以允许您调用 Python 命令。
    enter image description here

    假设我们有以下数据框,我们想用它来替换 ID 和 Name 列:
        new_name
    A   John_new
    B  Adams_new
    C     Mo_new
    D  Safia_new
    
    wb.sheets['Sheet1']['A1:B1'].value = df
    
    enter image description here

    最后,您可以保存并关闭。
    wb.save()
    wb.close()
    

    关于python - 使用 Pandas 修改 Excel 文件,布局更改最少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66421693/

    相关文章:

    Python - 根据总和对列表进行排序

    .net - 这是为 COM 注册 .NET 类型的一种可能方法吗

    python - 如何检测 Excel 工作表中的合并单元格?

    python - 尝试切片数据帧时出现类型错误 : unhashable type: 'list' ?

    python - 如何使用 OpenCV 检测图像中的波纹

    python - 如何在Django中拦截所有对数据库的读取查询?

    python - pip 安装本地 git 存储库

    excel - 获取excel列标题的算法说明

    python - 如何将 '?' 转换为 NaN

    python - 为什么在一种情况下 pandas 数据框的一列中的值变化快而在另一种情况下变化慢?