Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve original cell formatting in openpyxl

I am using openpyxl version 2.3.5 to write data into an existing, formatted, excel template (with .xlsx extension). The problem is that when I write to a cell, the formatting of that cell is completely overwritten. For example, Cell A1 has a blue fill. When I execute the following code:

wb = xl.load_workbook('Template.xlsx')
ws = wb.worksheets[0]
ws['A1'] = "TEST"
wb.save('test.xlsx')

The fill of cell A1 is lost. There is a lot of formatting in the spreadsheet, so I do not want to manually specify all of it. I have tried copying the original formatting of the cell from itself to no avail. This code did not work:

ws['A1'].style = ws['A1'].style

Is there any way to keep and/or copy the original style/formatting of the excel spreadsheet, and only write in the data?

like image 626
Sam Avatar asked May 02 '16 15:05

Sam


People also ask

How do I format a range of cells in openpyxl?

In openpyxl, each Cell object has a bunch of attributes we can use for formatting: Collectively, these attributes are called styles but I still prefer calling them just formats. One thing to note is that we can apply styles to only one cell at a time. So we’ll need to do a loop in order to format a range of cells.

How do I add a border to a cell in openpyxl?

OpenPyXL gives you the ability to style the borders on your cell. You can specify a different border style for each of the four sides of a cell. You can use any of the following border styles: Open your Python editor and create a new file named border.py. Then enter the following code in your file: This code will add a border to cell A1 and A3.

How to use fonts in openpyxl?

To see how you can use fonts in OpenPyXL, create a new file named font_sizes.py and add the following code to it: This code uses three different fonts in three different cells. In A1, you use the default, which is Calibri. Then in A2, you set the font size to Arial and increase the size to 14 points.

How does openpyxl read XML files?

Simply sad, openpyxl reads some xml files, then it parses that data, than you can use funtions in openpyxl library to change and add data, and finally when you save your workbook, openpyxl will create xml files, write data to them, and save them as zip archive (which is excel file).


1 Answers

I found that the formatting will be preserved in case the original cell did have a value previously. I am using "template" excels to fill out data and produce reports. Unfortunately with this method I need to have my template pre-populated with dummy values (creates huge size template files), also, need to make sure that dummy values are removed from the sheet from areas where I do not fill data into. its a pain, but at least the formatting remains in there

like image 176
syncofusion Avatar answered Sep 25 '22 10:09

syncofusion