How to copy the same formatting to different sheets of the same Excel file using the xlsxwriter
library in Python?
The code I tried is:
import xlsxwriterimport pandas as pd
import numpy as npfrom xlsxwriter.utility import xl_rowcol_to_celldf = pd.DataFrame()
df = pd.read_excel('TrendAnalysis.xlsx')# Create a Pandas Excel writer using XlsxWriter as the engine.
# Save the unformatted results
writer_orig = pd.ExcelWriter('TrendAnalysis.xlsx', engine='xlsxwriter')
df.to_excel(writer_orig, index=True)
writer_orig.save()work = ["isu-wise", "ISU-BFS", "ISU-CPG", "ISU-ER", "ISU-GE", "ISU-GOV Domestic", "ISU-GOV Overseas", "ISU-HC"]
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('TrendAnalysis.xlsx', engine='xlsxwriter')
for i in range(0,len(work)):df.to_excel(writer, index=True, sheet_name=work[i])# Get access to the workbook and sheetworkbook = writer.bookworksheet = writer.sheets[work[i]]print worksheet# We need the number of rows in order to place the totalsnumber_rows = len(df.index)# Total formattingtotal_fmt = workbook.add_format({'align': 'right', 'num_format': '#,##0','bold': True, 'bottom':6})# Add total rowsfor column in range(1,3):# Determine where we will place the formulacell_location = xl_rowcol_to_cell(number_rows+1, column)# Get the range to use for the sum formulastart_range = xl_rowcol_to_cell(1, column)end_range = xl_rowcol_to_cell(number_rows, column)# Construct and write the formulaformula = "=SUM({:s}:{:s})".format(start_range, end_range)worksheet.write_formula(cell_location, formula, total_fmt)# Add a total labelworksheet.write_string(number_rows+1, 0, "Total",total_fmt)i+=1writer.save()
workbook.close()
It creates the same sheet multiple times. Doesn't navigate and the sheets after the first one of the workbook. The code is error free and does the required formatting otherwise.