我想创建一个输入函数来创建表和多个工作表,但是它只把数据放在最后一个工作表中。如何在每个表格中放入数据,除了第一个称为"描述"的表格。
import xlsxwriter
from xlsxwriter import workbook
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet_description = workbook.add_worksheet( "description" )
sheetnames = input("Enter (sheets) names: ").split(", ")
for i in sheetnames:
worksheet_data = workbook.add_worksheet(i)
worksheet_data.write('A1', 'Number of table rows')
data = []
year = input("Enter years: ").split(", ")
q = ['q1 ' , 'q2 ', 'q3 ', 'q4 ']
for x in year:
for y in q:
data.append(x + y)
worksheet_data.write_row(0, 1, data)
col = input("Numerate columns (enter value): ").split(", ")
for i in col:
worksheet_data.write_column(1, 0, col)
workbook.close()
为什么不打印所有worksheet_data
的输入数据?
如果你想在每个工作表上写,你应该让程序在指定的工作表上工作。在您的代码中,for
循环已经完成,因此程序只在最后一个活动的工作表上打印您的数据。
这是我的脚本,打印在每一页,除了描述。
import xlsxwriter
from xlsxwriter import workbook
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet_description = workbook.add_worksheet( "description" )
sheetnames = input("Enter (sheets) names: ").split(", ")
year = input("Enter years: ").split(", ")
col = input("Numerate columns (enter value): ").split(", ")
for i in sheetnames: # Loop for each sheet
worksheet_data = workbook.add_worksheet(i)
worksheet_data.write('A1', 'Number of table rows')
data = []
q = ['q1 ' , 'q2 ', 'q3 ', 'q4 ']
for x in year:
for y in q:
data.append(x + y)
worksheet_data.write_row(0, 1, data)
for i in col:
worksheet_data.write_column(1, 0, col)
workbook.close()