读取包含合并单元格的Excel表格

待读取的.xlsx类型的表格中有合并单元格,为了对表格进行数据处理,需要将合并单元格进行拆分处理,所以进行如下处理:

def read_xlsx(file='./intent_data.xlsx', sheet_name=None, header=0):
    """读取 xlsx 格式文件。"""
    excel = pd.ExcelFile(load_workbook(file), engine="openpyxl")
    sheet_name = sheet_name or excel.sheet_names[0]
    sheet = excel.book[sheet_name]
    df = excel.parse(sheet_name, header=header)

    for item in sheet.merged_cells:
        top_col, top_row, bottom_col, bottom_row = item.bounds
        base_value = item.start_cell.value
        # 1-based index转为0-based index
        top_row -= 1
        top_col -= 1
        # 由于前面的几行被设为了header,所以这里要对坐标进行调整
        if header is not None:
            top_row -= header + 1
            bottom_row -= header + 1
        df.iloc[top_row:bottom_row, top_col:bottom_col] = base_value
    # 设置 pandas 输出选项以显示所有列
    pd.set_option('display.max_columns', None)

    # 设置 pandas 输出选项以显示所有行
    pd.set_option('display.max_rows', None)

    # 显示完整的 DataFrame
    # print(df)

    # 将 DataFrame 写入 Excel 文件
    df.to_excel(file.replace('.xlsx', '_split.xlsx'), index=False, engine="openpyxl")  # 如果您不希望保存索引,请将 index 参数设置为 False

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值