This is step by step tutorial that explains how to create python function for exporting data in Excel file.
To start programming in python you need to install python. In my previous article How To Create Your First Python Program I explained how to do it. After installing python you should install python package “xlwt”. Download xlwt from this LINK to some directory, for example site-packages . Open Command Prompt and navigate to site-packages/xlwt directory .
and run command :
python setup.py install
This command will run setup.py script which will add xlwt to your python
Now you can start programming. You can found complete code about export to excel function on my git hub account github.com/blaz1988/ExportToExcel/blob/master/excel.py
Let’s start programming…
First you need to import necessary packages
from xlwt import *
* import all functions from xlwt . Xlwt offer functions for writing data in excel files, adding sheets and similar…
Then you should define function , for example I define function with one argument. That argumet is list of data that will be exported to Excel
After that define your wokrbook and styles:
wbook = Workbook()
style1 = easyxf(
‘font: name Arial, bold yes, colour black, italic yes, height 180;’
‘alignment: vertical center, horizontal center, wrap yes;’
‘borders: left medium, right medium, top medium, bottom medium;’
‘pattern: pattern solid, fore_colour light_orange;’)
style2 = easyxf(
‘font: name Arial, colour black, height 180;’
‘alignment: vertical center, horizontal center, wrap yes;’)
Add sheet name with :
wsheet = wbook.add_sheet(sheetName)
You can define width of column, for example I define first column width with:
wsheet.col(0).width = 10000
To write data in Excel file use xlwt function called write, for example
wsheet.write(0, 0, “Website”, style1)
It writes string Website in column 0 and row 0 with style1.
You can call function with excel_fun(websites), where websites is variable structured as list that containes dictionaries
This function will export data from variable websites to excel file that looks like:
This function can be your “template” code for exporting data in excel. Function as argument accept list of dictionaries, which is format of JSON files , so it can take JSON file as argument too.
You can download complete code on github.com/blaz1988/ExportToExcel/