Python 如何创建一个 Excel 文件并向其写入内容?
目录
先说结论:推荐使用 openyxl 库,而不是 xlwt 库。使用 xlwt 库创建并向 .xls 文件写入内容时,其单个 sheet 限制最大行数为 65535。而使用 openpyxl 库创建并向 .xlsx 文件写入内容时,其单个 sheet 限制最大行数为 1048576,最大列数为 16384。
一、openpyxl 库
openyxl 库文档地址:https://openpyxl.readthedocs.io/en/stable/usage.html / https://pypi.org/project/openpyxl
import openpyxl
ExeclFileSavePath = "./test.xlsx"
wb = openpyxl.Workbook()
rowInit = 1
rowLimit = 50
columnInit = 1
columnLimit = 5
# 默认Sheet
ws = wb.active
for row in range(rowInit, rowLimit + 1):
for column in range(columnInit, columnLimit + 1):
ws.cell(row, column).value = row
# 创建一个sheet Pi
wsA = wb.create_sheet(title="Pi")
for row in range(rowInit, rowLimit):
wsA.append(range(columnInit, columnLimit))
# 保存文件
wb.save(ExeclFileSavePath)
二、xlwt 库
xlwt 库文档地址:https://xlwt.readthedocs.io/en/latest / https://pypi.org/project/xlwt
import xlwt
ExeclFileSavePath = "./test.xls"
workbook = xlwt.Workbook(encoding='utf-8')
sheet1 = workbook.add_sheet('sheet1', cell_overwrite_ok=True) # 给excel文件添加sheet
rowInit = 1
rowLimit = 50
columnInit = 1
columnLimit = 5
for row in range(rowInit - 1, rowLimit):
for column in range(columnInit - 1, columnLimit):
temp = row # 单元格内容
sheet1.write(row, column, temp)
# sheet1.write_merge(0, 3, 1, 1, '合并') # 合并单元格
workbook.save(ExeclFileSavePath)