1. 程式人生 > >python使用xlwt寫入excel

python使用xlwt寫入excel

def write_list_to_xls(file_name, sheet_name, message_list, firstcolumn_list, param_list):
    # file_name 檔名
    # sheet_name 表單名
    # message_list要寫入excel檔案的引數list
    # firstcolumn_list第一行引數中的值
    # param_list,message_list中每個元素的key值
    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet(sheet_name, cell_overwrite_ok=True)
    # 往第一行中寫資料
    first_column_count = 0
    for prompt in firstcolumn_list:
        sheet.write(0, first_column_count, prompt.decode('UTF-8'))
        first_column_count += 1
    # 開始寫後面的資料
    row_count = 1
    for message in message_list:
        # 第幾列
        temp_column_count = 0
        for key in param_list:
            sheet.write(row_count, temp_column_count, message.get(key))
            temp_column_count += 1
        # 行號遞增
        row_count += 1
    workbook.save(file_name)