我正在尝试使用XlsxWriter创建新工作表,以便在每次循环迭代时将数据写入新工作表。
我的代码如下:
workbook = xlsxwriter.Workbook('Report.xlsx')
for i in range(0, len(list)):
worksheet = workbook.add_worksheet()
#Extract data from the list and add it to the excel sheet
workbook.close()
现在,这种方法的问题是我只看到一个工作表,而不是多个工作表。
我哪里错了?
答案 0 :(得分:3)
根据评论的更正,即使XlsxWriter API允许在修改之间关闭工作簿,它也只会在第一次关闭之前写入更改。
import xlsxwriter
import openpyxl
workbook = xlsxwriter.Workbook('test.xlsx')
for i in range(10):
workbook.add_worksheet()
workbook.close()
assert len(workbook.worksheets()) == 10
assert len(openpyxl.load_workbook('test.xlsx').sheetnames) == 1
workbook = xlsxwriter.Workbook('test.xlsx')
for i in range(10):
workbook.add_worksheet()
workbook.close()
assert len(workbook.worksheets()) == 10
assert len(openpyxl.load_workbook('test.xlsx').sheetnames) == 10
在完成所有工作簿修改后,您需要将workbook.close()
移出循环:
workbook = xlsxwriter.Workbook('Report.xlsx')
for i in range(0, len(list)):
worksheet = workbook.add_worksheet()
#Extract data from the list and add it to the excel sheet
workbook.close()