Python Excel

Home   openpyxl Tutorial   Contact us

Python Excel Writer: Create, Write(Text, Number, Formula), Modify, Save, Apply settings, Merge- unmerge cells and more


Python Excel Training


With the help of openpyxl module we can also write to excel file in python. The process is somewhat similar to reading an excel spreadsheet in python. With python Excel writer, we will Create excel sheets, write text, numbers and formula in cells. After modifying we will save workbook. We will also add and delete sheets in a an excel workbook, apply setting, fonts and styles, set width and height of cells and areas, merge and unmerge cells. We can create any type of excel file, having hundreds and thousands of columns and rows of data. Writing to excel files is a necessity which no one can deny. There may be many cases for all professionals from a computer operator to a data scientist that one has to write to an excel spreadsheet in python. Here is the solution.

If you want to Read, Write and Manipulate(Copy, cut, paste, delete or search for an item or value etc) Excel files in Python with simple and practical examples I will suggest you to see this simple and to the point Python Excel Openpyxl Course with examples about how to deal with MS Excel files in Python. This video course teaches efficiently how to manipulate excel files and automate tasks.

Everything you do in Microsoft Excel, can be automated with Python. So why not use the power of Python and make your life easy. You can make intelligent and thinking Excel sheets, bringing the power of logic and thinking of Python to Excel which is usually static, hence bringing flexibility in Excel and a number of opportunities.

Automate your Excel Tasks and save Time and Effort. You can save dozens or hundreds of hours by Python Excel Automation with just a single click get your tasks done with in seconds which used to take hours of Manual Excel and Data Entry Work.

Python Excel Create and Save files:

 
First we will learn how to create and save excel files with python. First we will create an excel file.

First step will be to import openpyxl module.

>>> import openpyxl

Next we will create an excel file or technically a Workbook.

>>> mywb = openpyxl.Workbook()


The above code will create a work book with one sheet in the beginning. We can check the number of sheets with the following code, see which sheet is active and what is the title of the active sheet. In this case we have only one sheet, hence it will be the only answer.

>>> mywb.get_sheet_names()

['Sheet']

>>> sheet = mywb.active

>>> sheet.title

'Sheet'

We can also set the title of the sheet, see the example given below.

>>> sheet.title = 'MyNewTitle'

>>> wb.get_sheet_names()

['MyNewTitle']

>>>mywb.save('NewExcelFile.xlsx')

If you open your root folder or current working directory, you will find a new excel file, with name NewExcelFile, having one sheet with title MyNewTitle.

Loading an already existing excel file in Python and saving a copy of it:

Whenever you load an already existing Excel file in memory, and modify the contents, either sheets or cells, or creating whole sheets, or deleting sheets, or any modification which could be done, you will have to call save( ) method to save the file. If you don't do so, any modification will be lost. 

>>> import openpyxl

>>> mywb = openpyxl.load_workbook('filetest.xlsx')

>>> sheet = mywb.active

>>> sheet.title = 'Working on Save as'

>>> mywb.save('example_filetest.xlsx')

In the code above you noticed that we loaded already existing file, changed sheet title and saved its copy with a different name. In this case original file plus this new file will be in your working directory, which is usually your python root folder. Open it and see the new copy. 

When you work on an excel spreadsheet in python, its always better to save it with a different file name, so that the original is always there, in case any mishap happens, for example any bug in code, or mistake in saving, or writing.

Creating and Removing Sheets in Excel:


For creating new sheets in a workbook, we use create_sheet( ) method. 

For deleting a sheet we use remove_sheet( ) method.

>>> import openpyxl

>>> mywb = openpyxl.Workbook()

>>> mywb.get_sheet_names()

['Sheet']

>>> mywb.create_sheet()

<Worksheet "Sheet1">

>>> mywb.get_sheet_names()

['Sheet', 'Sheet1']

>>> wb.create_sheet(index=0, title='1st Sheet')

<Worksheet "1st Sheet">

>>> mywb.get_sheet_names()

['1st Sheet', 'Sheet', 'Sheet1']

>>>mywb.create_sheet(index=2, title='2nd Sheet')

<Worksheet "2nd Sheet">

>>>mywb.get_sheet_names()

['1st Sheet', 'Sheet', '2nd Sheet', 'Sheet1']

Create sheet creates a new sheet, which is by default the last sheet in the workbook. However, we can specify the position of the new sheet with index number and we can also pass a string as the title of new sheet. Keep in mind, the first sheet will have index 0, second will have index 1 and so on.

Removing sheets from Excel Workbook:

When we want to remove any specific sheet from an excel workbook, we will use method remove_sheet( )


>>>mywb.get_sheet_names()

['1st Sheet', 'Sheet', '2nd Sheet', 'Sheet1']

This is to see the number of sheets and their names, now working with removing or deleting sheets.

>>> mywb.remove_sheet(mywb.get_sheet_by_name('1st Sheet'))

>>> mywb.remove_sheet(mywb.get_sheet_by_name('Sheet1'))

>>> mywb.get_sheet_names()

['Sheet', '2nd Sheet']

It is very obvious that after deleting the two sheets from four sheets, only two sheets are left. remove_sheet method takes a worksheet object not name of the sheet, instead of creating an object to that specific worksheet and then removing it, we call get_sheet_by_name( ) and pass it the name of sheet, the value it returns is the input argument of remove_sheet( ) method. In the end, use save( ) method to save the file after modification. In this case removal of worksheets.


Python excel Writing Values in Cells:

Now we will see how to write values to particular cells in an excel worksheet. Ofcourse we should know the address of the cell where we want to write. 

>>> import openpyxl

>>> mywb = openpyxl.Workbook()

>>> mysheet = mywb.get_sheet_by_name('Sheet')

>>> mysheet['F6'] = 'Writing new Value!'

>>> mysheet['F6'].value    

'Writing new Value'


Python Excel setting Fonts:

Applying different styles to your sheet, emphasizes or stresses certain rows or columns. It is very important to apply certain uniform styles to your excel sheets so that it brings clarity in reading the data. If you have hundreds or thousands of rows of data, styling can be a hectic job, however, with our python code, you can write a few lines of code and apply on millions of lines of data instantly. But take care, first styling should be with absolute care, and second always save excel workbook with a different name.

First we will import openpyxl, and then import Font and Style for use in our code.

Here’s an example that creates a new workbook and sets cell F6 to have a 32-point, italicized font. 

 

 >>> import openpyxl

>>> from openpyxl.styles import Font, Style

>>> mywb = openpyxl.Workbook()

>>> mysheet = mywb.get_sheet_by_name('Sheet')

>>> italic32Font = Font(size=32, italic=True)

>>> sobj = Style(font=italic24Font)

>>> mysheet['F6'].style = sobj

>>> mysheet['F6'] = 'Applying Styles!'

>>> mywb.save('Appliedstyle.xlsx')

In openpyxl for excel worksheets each cell has a style object which is in style attribute of the cell. We create a style object and assign it to style attribute.

There are four arguments for Font objects

  • Name: A string value is used, quoting the font name, like 'Arial'.
  • Size: An integer value, quoting the size.
  • Bold: A boolean value, True for Bold font.
  • Italic: Boolean value, True for Italic font.

In the example below we will call Font( ) method to create a Font object and store it in a variable, next step will be to pass that as an argument to Style( ) method. We will store the that object in another variable and assign it to the specific cell object.
 

 

>>> import openpyxl

>>> from openpyxl.styles import Font, Style

>>> mywb = openpyxl.Workbook()

>>> mysheet = mywb.get_sheet_by_name('Sheet')

 

>>> firstFontObj = Font(name='Arial', bold=True)

>>> firstStyleObj = Style(font=firstFontObj)

>>> mysheet['F6'].style/firstStyleObj

>>> mysheet['F6'] = 'Bold Arial'

 

>>> secondFontObj = Font(size=32, italic=True)

>>> secondStyleObj = Style(font=secondFontObj)

>>> mysheet['D7'].style/secondStyleObj

>>> mysheet['D7'] = '32 pt Italic'

 

>>> mywb.save('ApplicationofStyles.xlsx')

Python Excel Writing Formulae:


Formulae in Excel are very important, infact the power of a spreadsheet is in its formulae. Openpyxl provides the utility of writing formula in any specific cell. Infact it is very much easy, instead of writing a number or text, write an equal sign followed by the required formula.

>>>mysheet['F6'] = '=Sum(D7:D20)'

This formula will sum up all values from D7 to D20 and store in F6 cell.

Some more examples:


>>> import openpyxl

>>> mywb = openpyxl.Workbook()

>>> mysheet = mywb.active

>>> mysheet['F6'] = 500

>>> mysheet['F7'] = 800

>>> sheet['D3'] = '=SUM(F6:F7)'

>>> mywb.save('Applyingformula.xlsx')

In the above example we put 500 in F6, and 800 in F7 cell. Cell D3 has a formula of adding up F6 and F7. When you will open spreadsheet, it will show a value of 1300 in D3.

The cells in A1 and A2 are set to 200 and 300, respectively. The value in cell A3 is set to a formula that sums the values in A1 and A2. When the spreadsheet is opened in Excel, A3 will display its value as 500.


Excel Adjusting Rows and Columns in a Sheet:


We can set Row heigh, column width in excel spreadsheet using openpyxl. We can also freeze rows or columns so that they always appear. We can also hide rows or columns.

>>> import openpyxl

>>> mywb = openpyxl.Workbook()

>>> mysheet = mywb.active

>>> mysheet['F6'] = 'Tall row'

>>> mysheet['D7'] = 'Wide column'

>>> mysheet.row_dimensions[3].height = 65

>>>mysheet.column_dimensions['F'].width = 25

>>>mywb.save('Heightandwidth.xlsx')


The default row height in excel spreadsheet is 12.75 points. Where one point is equal to 1/72 of an inch. You can set a value between 0 to 409.

Column width can be set to a value from 0 to 255. It can be either an integer or a floating value (decimal number). If you set 0 width for column or 0  height for rows, it will be hidden. 


Excel Merging and unmerging

openpyxl allows us to merge and unmerge cells in a workbook. 

>>> import openpyxl

>>>my wb = openpyxl.Workbook()

>>> mysheet = mywb.active

>>> mysheet.merge_cells('B2:D3')

>>> mysheet['A1'] = 'cells merged together.'

>>> mysheet.merge_cells('F6:F7')

>>> mysheet['G5'] = 'Two merged cells.'

>>> mywb.save('Mergingcells.xlsx')

merge_cells method takes two cell addresses as its arguments. First cell is the top left and second cell is the right bottom of the rectangular area that is to be merged. If we want to set value of that merged area, we use the address of top left cell of the whole merged area.

 

If you want to unmerge cells, use the idea below.


>>> import openpyxl

>>> mywb = openpyxl.load_workbook('Mergingcells.xlsx')

>>> mysheet = mywb.active

>>> mysheet.unmerge_cells('B2:D3')

>>> mysheet.unmerge_cells('F6:F7')

>>> mywb.save('unmerged.xlsx')    


If you want to Read, Write and Manipulate(Copy, cut, paste, delete or search for an item or value etc) Excel files in Python with simple and practical examples I will suggest you to see this simple and to the point Python Excel Openpyxl Course with examples about how to deal with MS Excel files in Python. This video course teaches efficiently how to manipulate excel files and automate tasks.

Everything you do in Microsoft Excel, can be automated with Python. So why not use the power of Python and make your life easy. You can make intelligent and thinking Excel sheets, bringing the power of logic and thinking of Python to Excel which is usually static, hence bringing flexibility in Excel and a number of opportunities.

Automate your Excel Tasks and save Time and Effort. You can save dozens or hundreds of hours by Python Excel Automation with just a single click get your tasks done with in seconds which used to take hours of Manual Excel and Data Entry Work.