Python Excel |
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.
First step will be to import openpyxl module.
>>> import openpyxl
Next we will create an excel file or technically a Workbook.
>>> mywb = openpyxl.Workbook()
>>> 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.
>>> 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.
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.
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.
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'
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
>>> 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')
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.
>>> 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')
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.