问题
This is the basic flow that my Python script is following with XLSXwriter:
- Create Workbook
- Create Worksheet
- Define Formatting
- Write Column Headers in row1 (leveraging formatting from Step3)
- Write Actual Data in subsequent rows (no special formatting)
I can create the workbook/worksheet. I then define formatting and populate worksheet row1 columns A:H with 'COLUMN HEADERS' which signify the type of DATA that will be written into each column on subsequent rows. This much is a success.
My code and problem description are below:
# write column header information
if total_xls_records == 1:
worksheet1.set_row(0, 15, header_format)
worksheet1.set_column('A:H',30)
worksheet1.write('A1', 'Hostname')
worksheet1.write('B1', 'Serial')
worksheet1.write('C1', 'Manufacturer')
worksheet1.write('D1', 'Model')
worksheet1.write('E1', 'RAM')
worksheet1.write('F1', 'Flash')
worksheet1.write('G1', 'Version')
worksheet1.write('H1', 'SW_Image')
# write device data to spreadsheet
else:
worksheet1.set_row(total_xls_records, 15)
worksheet1.set_column('A:H',30)
worksheet1.write('A2', data[0])
worksheet1.write('B2', data[1])
worksheet1.write('C2', data[2])
worksheet1.write('D2', data[3])
worksheet1.write('E2', data[4])
worksheet1.write('F2', data[5])
worksheet1.write('G2', data[6])
worksheet1.write('H2', data[7])
I'm pulling data in from a list to populate my cells. The result of this if/else is:
- When I match the "if" statement, the column headers get written to spreadsheet properly
If I open the spreadsheet, I see row1 columns A:H properly populated and formatted per header_format with a column width of 30.
- When I subsequently match the "else" statement, the spreadsheet is overwritten
If I open the spreadsheet, I see row1 is completely empty (all column headers/formatting are now gone) and row2 is properly populated with device DATA (no formatting).
Obviously the desired behavior is to have row1 with COLUMN HEADERS and rows2-whatever with DATA. I want to 'append' DATA to the spreadsheet in rows2-whatever AFTER row1 has already been written.
Yes, I'm aware that the else statement currently calls a 'static list' of cells (A2-H2) and that this means multiple matches of else will currently write DATA into the same set of cells. It's currently written this way because I'm in 'troubleshooting mode' for the problem I just described. For me it makes sense to fix the spreadsheet overwrite problem before re-writing my "cell population" code.
Thanks in advance for any help provided.
回答1:
XlsxWriter cannot rewrite a file or repeatedly save to a file.
Once workbook.close()
is called the file is written and closed.
来源:https://stackoverflow.com/questions/26183941/python-with-xlsxwriter-spreadsheet-overwritten