欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python合并单元格

程序员文章站 2022-06-14 09:26:46
...

python合并单元格,按行写数据

import xlwt
def write_excel_merge_cell(headers, data, merge_lt, file_name):
    '''
    合并单元格
    :param headers: 表头
    :param data: 数据
    :param merge_lt:合并单元格数据
    :param file_name: 文件名字
    :return:
    '''

    f = xlwt.Workbook()
    sheet1 = f.add_sheet('sheet1', cell_overwrite_ok=True)
    # 表头
    for i in range(0, len(headers)):
        sheet1.write(0, i, headers[i])

    # 根据单元格数据长度决定合并单元格

    x = 0
    y = 0
    line_len = 0
    i, j = 0, 0
    # 遍历数据
    for item in data:

        index = data.index(item)

        for j in range(len(item)):
            # 查看改行对应合并单元格的数量
            line_len = len(merge_lt[index])

            ss = item[j]

            if line_len != 0:
                # r1:开始行 r2:结束行 c1:开始列 c2:结束列 label数据
                sheet1.write_merge(i + 1, i + line_len, j, j, ss)
            else:
                sheet1.write_merge(i + 1, i + 1, j, j, ss)
        x += 1
        i += line_len
        # 判断和并单元格列是否有数据
        if len(merge_lt[index]):

            for z in range(0, len(merge_lt[index])):
                if len(merge_lt[index][z]):
                    for ks in merge_lt[index][z]:
                        sheet1.write(y + 1, len(item) + merge_lt[index][z].index(ks), ks)
                    y += 1
                else:
                    y += 1
        else:
            y += 1

    # 保存
    file_name = file_name
    f.save(file_name)


def main():
    # 标题
    headers = ['序号', "姓名", '列表', '1月', '2月', '3月', '4月', '5月']
    # 写入数据
    data = [['1', 'lz', 'l', 'z', 'm'], ['2', 'lz2', 'l2', 'z2', 'm2'], ['3', 'lz3', 'l3', 'z3', 'm3'],
            ['4', 'lz4', 'l4', 'z4', 'm4']]
    # 对应data数据的合并单元格数据
    merge_lt = [
        [['券优免', -100.0], ['累计专项扣除-五险一金', 22], ['累计免税收入', 33], ['累计扣个税', 33]],
        [['累计应发数', 1001], ['累计专项扣除-五险一金', 10002], ['累计免税收入', 10003]],
        [['累计应发数', 1001], ['累计专项扣除-五险一金', 10002]],
        [['累计应发数', 1001]]
    ]

    #文件名
    file_name = 'test6.xlsx'
    write_excel_merge_cell(headers, data, merge_lt, file_name)


if __name__ == '__main__':
    main()