Python操作Excel合并单元格

时间:2022-07-24
本文章向大家介绍Python操作Excel合并单元格,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

每门编程语言都会遇到操作Excel!本文主要说下Python对Excel操作时合并单元格的情况。

目录

1.效果图

2.用到的方法

3.完整代码

1

效果图

2

用到的方法

Python中操作Excel的库有很多,本次使用 xlsxwriter 来进行写Excel操作。Python版本 3.6。

xlsxwriter 可直接 pip 安装。新建一个Excel,里面可包含多个sheet ,程序中要对具体工作sheet进行操作,这个就像在windows下操作Excel一样。

add_worksheet 添加一个sheet
add_format 添加一个样式,比如 居中,居左等
write 写一行数据
merge_range('A1:A7') 合并单元格,A2-A7
set_column 设置列的宽度等

3

完整代码

import os
import xlsxwriter

def get_history():

    # write excel,construct dict
    filename = '333.xlsx'
    # 删除结果文件
    if (os.path.isfile(filename)):
        os.remove(filename)

    list = {}

    # 注意 python字典里面不能再嵌入字典!
    list['name1'] = []
    list['name1'].append({
            'title': 'title-1-1',
            'comments': [{'content': 'comments-name-1-1', 'created_at': '2020-04-13 12:17:10'},{'content': 'comments-name-1-2', 'created_at': '2020-04-13 12:17:10'}]
        }
    )

    list['name1'].append({
        'title': 'title-1-2',
        'comments': [{'content': 'comments-name-1-2', 'created_at': '2020-04-13 12:17:10'},
                     {'content': 'comments-name-1-3', 'created_at': '2020-04-13 12:17:10'}]

    }
    )

    list['name2'] = []
    list['name2'].append(
        {
           'title':'title-2-1',
           'comments':[{'content':'comments-name-2-1','created_at':'2020-04-13 12:17:10'},{'content':'comments-name-2-2','created_at':'2020-04-13 12:17:10'},{'content':'comments-name-2-3','created_at':'2020-04-13 12:17:10'}]
        }
    )

    list['name3'] = []
    list['name3'].append(
        {
            'title': 'title-3-1',
            'comments': [{'content': 'comments-name-3-1', 'created_at': '2020-04-13 12:17:10'}]
        }
    )

    write_to_excel(filename,list)

def write_to_excel(output,list):

    workbook = xlsxwriter.Workbook(output)

    # define sheet name
    sheetName = 'History and Comment'
    worksheet_s = workbook.add_worksheet(sheetName)

    # 为单元格设置样式
    header = workbook.add_format({
        'bg_color': '#F7F7F7',
        'color': 'black',
        'align': 'center',
        'valign': 'top',
        'border': 1
    })

    merge_format = workbook.add_format({
        'bold': True,
        'border': 6,
        'align': 'center',  # 水平居中
        'valign': 'vcenter',  # 垂直居中
        'fg_color': '#D7E4BC',  # 颜色填充
    })

    bold_cell = workbook.add_format({
        'bold': True,
        'align': 'left',
        'valign': 'top',
        'text_wrap': True,
        'border': 1
    })

    cell = workbook.add_format({
        'align': 'left',
        'valign': 'top',
        'text_wrap': True,
        'border': 1
    })


    # 以下为其他几种样式
    bold_header = workbook.add_format({
        'bold': True,
        'bg_color': '#F7F7F7',
        'color': 'black',
        'align': 'center',
        'valign': 'top',
        'border': 1
    })


    cell_center = workbook.add_format({
        'align': 'center',
        'valign': 'top',
        'border': 1
    })

    title = workbook.add_format({
        'bold': True,
        'font_size': 14,
        'align': 'center',
        'valign': 'vcenter'
    })

    # 标题
    header_define = ['Name', 'Titile', 'Commit Date','Comments']

    for i in range(0, len(header_define)):
        worksheet_s.write(0, i, header_define[i], header)

    a_col_width = 50
    b_col_width = 50
    c_col_width = 50
    d_col_width = 50
    # add data into the table
    data_row = 1
    data_row_2 = 1
    data_row_1 = 1

    for one_name in list.keys():

        #先写 第 3,4 列
        for one_history in list[one_name]:
            print(one_history)
            for one_comment in one_history['comments']:
                worksheet_s.write_string(data_row, 2, one_comment['created_at'], bold_cell)
                worksheet_s.write_string(data_row, 3, one_comment['content'], cell)
                data_row = data_row+1
            #写第二列
            historys_len = len(one_history['comments'])
            if historys_len == 1:
                worksheet_s.write_string(data_row_2, 1, one_history['title'], bold_cell)
                data_row_2 = data_row_2 + 1
            else:
                print('B'+str(data_row_2)+':B'+str(data_row_2+historys_len))
                worksheet_s.merge_range('B'+str(data_row_2+1)+':B'+str(data_row_2+historys_len), one_history['title'], merge_format)
                data_row_2 = data_row_2+historys_len

        # 写第一列
        if data_row_2 - data_row_1 == 1:
            worksheet_s.write_string(data_row_1, 0, one_name, bold_cell)
        else:
            worksheet_s.merge_range('A' + str(data_row_1 + 1) + ':A' + str(data_row_2),one_name, merge_format)
        data_row_1 = data_row_2

    worksheet_s.set_column('A:A', a_col_width)
    worksheet_s.set_column('B:B', b_col_width)
    worksheet_s.set_column('C:C', c_col_width)
    worksheet_s.set_column('D:D', d_col_width)
    workbook.close()
    #xlsx_data = output.getvalue()
    #return xlsx_data


def test():
    excle1 = xlsxwriter.Workbook("test.xlsx")
    worksheet = excle1.add_worksheet()

    worksheet.write("A1", "hello world")
    excle1.close()

if __name__ == '__main__':
    get_history()

END

随机文章