Python openpyxl 创建Excel

要求:数据写入Excel的sheet中,文字居中,指定列宽

from openpyxl import Workbook
from openpyxl.styles import Alignment

#新建Excel
wb = Workbook()
#格式为居中
alignment_center = Alignment(horizontal='center', vertical='center')

#第0个sheet命名为sheet
ws = wb.create_sheet('sheet', 0)

#写入数据
ws['A1'] = 'XXXX'
ws['B1'] = 'XXXX'
ws['C1'] = 'XXXX'
ws['D1'] = 'XXXX'
ws['E1'] = 'XXXX'
ws['F1'] = 'XXXX'
ws['G1'] = 'XXXX'
ws['H1'] = 'XXXX'
ws['I1'] = 'XXXX'

#选择区域进行格式设置
ws_area = ws["A1:I1"]
        for i in ws_area:
            for j in i:
                j.alignment = alignment_center;
                
#设置列宽
ws.column_dimensions['A'].width = 9
ws.column_dimensions['B'].width = 50
ws.column_dimensions['C'].width = 13
ws.column_dimensions['D'].width = 8
ws.column_dimensions['E'].width = 8
ws.column_dimensions['F'].width = 30
ws.column_dimensions['G'].width = 28
ws.column_dimensions['H'].width = 28
ws.column_dimensions['I'].width = 28

#保存文件
wb.save('Mytest.xlsx')
wb.close()

Q.E.D.


一名北漂的网安工程师,希望这次能好好工作,不被毕业吧…