Center align using xlsxwriter (without conditional formatting) - python

Using xlsxwriter, one can write a dataframe 'df' to Excel 'simple.xlsx' using code such as:
import pandas as pd
writer = pd.ExcelWriter('simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
With above code, I see that the resultant Excel sheet has all cells (except header) as default left-aligned.
Question:
How can I make the Excel cell values to be center-aligned?
I did explore using conditional formatting but, with my cell values being combination of blanks, zeros, floats, strings and integers, I am wondering if there is another way.
Is there a smarter/quick way to do either/both of the following:
Any way to write dataframe to Excel as center-aligned? Or..
Any way to center-align the Excel sheet (for the cell range occupied by dataframe) once the dataframe has already been written to Excel?

You can add the below line to your code
df=df.style.set_properties(**{'text-align': 'center'})
Your complete code would be
import pandas as pd
writer = pd.ExcelWriter('simple.xlsx', engine='xlsxwriter')
df=df.style.set_properties(**{'text-align': 'center'})
df.to_excel(writer, sheet_name='Sheet1')
writer.save()

Related

How to export python dataframe into existing excel sheet and retain formatting?

I am trying to export a dataframe I've generated in Pandas to an Excel Workbook. I have been able to get that part working, but unfortunately no matter what I try, the dataframe goes into the workbook as a brand new worksheet.
What I am ultimately trying to do here is create a program that pulls API data from a website and imports it in an existing Excel sheet in order to create some sort of "live updating excel workbook". This means that the worksheet already has proper formatting, vba, and other calculated columns applied, and all of this would ideally stay the same except for the basic data in the dataframe I'm importing.
Anyway to go about this? Any direction at all would be quite helpful. Thanks.
Here is my current code:
file='testbook.xlsx'
writer = pd.ExcelWriter(file, engine = 'xlsxwriter')
df.to_excel(writer, sheet_name="Sheet1")
workbook = writer.book
worksheet = writer.sheets["Sheet1")
writer.save
In case u have both existing excel file and DataFrame in same format then you can simply import your exiting excel file into another DataFrame and concat both the DataFrames then save into new excel or existing one.
df1["df"] = pd.read_excel('testbook.xlsx')
df2["df"] = 1#your dataFrame
df = pd.concat([df1, df2])
df.to_excel('testbook.xlsx')
There are multiple ways of doing it if you want to do it completely using pandas library this will work.

Pandas Excel Writer append mode is not working

I created a pandas dataframe in my code and tried to append the final output to an existing Excel workbook. The existing workbook is called "Directory" and has three different sheets in it. I want to append my output to one of the sheets called "raw_data in the workbook". This sheet already has some data in it but the columns in this sheet match the columns in my new dataframe. Here is my code:
from pandas import ExcelWriter
from pandas import ExcelFile
from openpyxl import Workbook
with pd.ExcelWriter(r'C:\Users\Documents\Directory.xlsx', engine ='openpyxl', mode='a') as writer:
df.to_excel(writer, sheet_name = 'raw_data', index = False, header = False)
writer.save()
writer.close()
My code "runs" without any error but when I check the workbook after running the code, my code doesn't append my data frame to the specified sheet, "raw_data", but creates a new sheets called "raw_data1" and store the data in that tab. I couldn't figure out which part in my code is incorrect. Could anyone please help me with this? Thank you.

Add border to excel using pandas

I need to add a border around my dataframe which i have created using pandas as shown in the attached pictureExcelTableImage. Below is my code snippet. How can this be done?
[df = pd.DataFrame(data)
df2=pd.DataFrame(exportFields)
df2 = df2.transpose()
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('C:/Users/roshni.j/Desktop/Clarivoy_docs/Testing/pandas_simple.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df2.to_excel(writer, sheet_name='Sheet1',index=False, header=False,startcol=1, startrow=2)
df.to_excel(writer, sheet_name='Sheet1',index=False, header=False,startcol=1, startrow=3)
# Close the Pandas Excel writer and output the Excel file.
writer.save()
You need to use something like StyleFrame for this (https://styleframe.readthedocs.io/en/latest/). Pure pandas can't draw any frames in Excel.
Use add_table method from pandas then you can style it.
https://xlsxwriter.readthedocs.io/working_with_tables.html

Python : How to write on existing xlsx without overwrite other columns

I just want to overwrite certain column base on my dataframe. Suppose df2 is my dataframe.
Below is the code i use. The problem is its overwrite the other columns and row even though i code it to start on columns 80.
I want its overwrite on column 80 and beyond only, but not before the column 80. 80 is index, not name.
import pandas as pd
import xlsxwriter
df2 = pd.read_excel(r'C:\Users\RUI LEONHART\Google Drive\Shop\STOCK V2.xlsx',
usecols=['XS1','S1','M1','L1','XL1','XXL1'])
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df2.to_excel(writer, sheet_name='Sheet1', startcol=80)
# Get the xlsxwriter objects from the dataframe writer object.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Close the Pandas Excel writer and output the Excel file.
writer.save()
I search around the solution. The closest one is this
python: update dataframe to existing excel sheet without overwriting contents on the same sheet and other sheets
but still overwrite the columns and row that i dont want.

How to add a dataframe to an existing Excel sheet with Pandas, on a .xlsm file

I want to import the values from a Pandas dataframe into an existing Excel sheet. I want to insert the data inside the sheet without deleting what is already there in the other cells (like formulas using those datas etc).
I tried using data.to_excel like:
writer = pd.ExcelWriter(r'path\TestBook.xlsm')
data.to_excel(writer, 'Sheet1', startrow=1, startcol=11, index = False)
writer.save()
The problem is that this way i overwrite the entire sheet.
Is there a way to only add the dataframe? It would be perfect if I could also keep the format of the destination cells.
Thanks
I found a good solution for it. Xlwings natuarally supports pandas dataframe:
https://docs.xlwings.org/en/stable/datastructures.html#pandas-dataframes
The to_excel function provides a mode parameter to insert (w) of append (a) a data frame into an excel sheet, see below example:
with pd.ExcelWriter(p_file_name, mode='a') as writer:
df.to_excel(writer, sheet_name='Data', startrow=2, startcol=2)

Categories

Resources