Formatting multiple worksheets using xlsxwriter

2024/10/7 6:41:32

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.

Answer

It may be too late but here is what I have done for this. In my example I have 2 DataFrame which I would like to freeze the pane, add filter to each column, and format the header of both sheets which are being saved on the same excel file.

writer = pd.ExcelWriter(path_of_excel_file+'output.xlsx')
sheets_in_writer=['Sheet1','sheet2']
data_frame_for_writer=[df1, df2]for i,j in zip(data_frame_for_writer,sheets_in_writer):i.to_excel(writer,j,index=False)### Assign WorkBook
workbook=writer.book
# Add a header format
header_format = workbook.add_format({'bold': True,'text_wrap': True,'size':10,'valign': 'top','fg_color': '#c7e7ff','border': 1})
### Apply same format on each sheet being saved
for i,j in zip(data_frame_for_writer,sheets_in_writer):for col_num, value in enumerate(i.columns.values):writer.sheets[j].write(0, col_num, value, header_format)writer.sheets[j].autofilter(0,0,0,i.shape[1]-1)writer.sheets[j].freeze_panes(1,0)
writer.save()
https://en.xdnf.cn/q/70277.html

Related Q&A

Good python library for generating audio files? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

Keras ConvLSTM2D: ValueError on output layer

I am trying to train a 2D convolutional LSTM to make categorical predictions based on video data. However, my output layer seems to be running into a problem:"ValueError: Error when checking targe…

debugging argpars in python

May I know what is the best practice to debug an argpars function.Say I have a py file test_file.py with the following lines# Script start import argparse import os parser = argparse.ArgumentParser() p…

Non-blocking server in Twisted

I am building an application that needs to run a TCP server on a thread other than the main. When trying to run the following code:reactor.listenTCP(ServerConfiguration.tcpport, TcpCommandFactory()) re…

Reading changing file in Python 3 and Python 2

I was trying to read a changing file in Python, where a script can process newly appended lines. I have the script below which prints out the lines in a file and does not terminate.with open(tmp.txt,r)…

How to remove timestamps from celery pprint output?

When running the celery worker then each line of the output of the pprint is always prefixed by the timestamp and also is being stripped. This makes it quite unreadable:[2015-11-05 16:01:12,122: WARNIN…

How to get max() to return variable names instead of values in Python?

So I would like to get the maximum value from 3 variables, x,y,z.x = 1 y = 2 z = 3 max(x, y, z) # returns 3 but I want "z"However this returns the value of z i.e 3. How do I get the name of …

SymPy Imaginary Number

Im messing around with writing some SymPy code to handle symbolic expressions with imaginary numbers.To start out, I want to get it to take x and y as real numbers and find the solution where x=iy. So …

Django 1.11 404 Page while Debug=True

Without making things difficult, I just want to show a special 404 render with staticfiles.If you set DEBUG = False you can use in urls.pyhandler404 = app.views.handler404But it is without staticfiles.…

zip()-like built-in function filling unequal lengths from left with None value

Is there a built-in function that works like zip(), but fills the results so that the length of the resulting list is the length of the longest input and fills the list from the left with e.g. None?Th…