python3寫excel之xlsxwriter
阿新 • • 發佈:2022-12-02
pip install xlsxwriter
xlsxwriter 生成的檔案字尾名為.xlsx,最大能夠支援 1048576 行資料,16384 列資料
import os import xlsxwriter import datetime if os.path.exists('./gen-files/demo.xlsx'): os.remove('./gen-files/demo.xlsx') workbook = xlsxwriter.Workbook('./gen-files/demo.xlsx') sheet = workbook.add_worksheet('sheet1') style_cell= workbook.add_format({ 'font_name': 'Microsoft Yahei', 'font_size': 14, 'bold': False, 'align': 'center', 'valign': 'vcenter', 'text_wrap': False }) for i in range(5): for j in range(4): sheet.write_number(i, j, i+j, style_cell) # 公式 sheet.write_formula(i, 4, "=sum(A"+str(i+1)+":D"+str(i+1)+")", style_cell) # 空白 sheet.write_blank(i, 5, None, style_cell) # 字串 sheet.write_string(i, 6, 'Baidu', style_cell) # 日期格式 sheet.write_datetime(i, 7, datetime.datetime.now(), style_cell) # Boolean格式 sheet.write_boolean(i, 8, True, style_cell)# url sheet.write_url(i, 9, 'https://www.baidu.com/', style_cell) # rich text # sheet.write_rich_string(i, 7, 'aa', style_cell) sheet = workbook.add_worksheet('sheet2') # 合併單元格 sheet.merge_range('A1:D1', 'TEST') sheet.write('A2', 4) sheet.write(3, 1, 4) # 公式 sheet.write(3, 2, "=sum(A"+str(i+1)+":D"+str(i+1)+")") sheet = workbook.add_worksheet('sheet3') header = ['name', 'age', 'score'] # 寫入整行 sheet.write_row('A1', header) # 寫入整列 names = ['lily', 'rose', 'susan', 'john', 'jack'] sheet.write_column('A2', names) sheet.write_column('B2', range(6, 11, 1)) sheet.write_column('C2', range(75, 100, 5)) chart = workbook.add_chart({'type': 'line'}) chart.add_series({ 'name': '=sheet3!$B$1', 'categories': '=sheet3!$A$2:$A$6', 'values': '=sheet3!$B$2:$B$6', 'line': {'color': 'green'} }) chart.add_series({ 'name': '=sheet3!$C$1', 'categories': '=sheet3!$A$2:$A$6', 'values': '=sheet3!$C$2:$C$6', 'line': {'color': 'blue'} }) chart.set_title({'name': '折線圖'}) chart.set_x_axis({'name': 'xAxis'}) chart.set_y_axis({'name': 'yAxis'}) sheet.insert_chart('A8', chart, {'x_offset': 25, 'y_offset': 25}) workbook.close()