欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用Python的openpyxl库写入数据到Excel表格

最编程 2024-01-06 11:32:13
...
# 说明:需要写入的是二维列表target_data
# 将数据写入excel表格
workbook = openpyxl.Workbook()
sheet0 = workbook.create_sheet(index=0) # 创建sheet0
sheet0.column_dimensions['A'].width=15 # 设置A列宽度
sheet0.column_dimensions['B'].width=22 # 设置B列宽度
sheet0.column_dimensions['C'].width=15 # 设置C列宽度
sheet0.column_dimensions['D'].width=15 # 设置D列宽度
# 循环写入数据,居中对齐
for i in range(len(target_data)):
for j in range(len(target_data[i])):
sheet0.cell(i+1,j+1).value = target_data[i][j] # 写入数据
sheet0.cell(i+1,j+1).alignment = Alignment(horizontal='center', vertical='center') # 居中对齐
workbook.save('test.xlsx') # 保存文件

推荐阅读