BREAKING NEWS

main-nav-top (Do Not Edit Here!)

Tuesday, January 14, 2014

How To Create Python Export To Excel Function

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 pythonpackage “xlwt”. Download xlwt from this LINK to some directory, for example site-packages . OpenCommand Prompt and navigate to site-packages/xlwt directory .
install-xlwt
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 glob
import os
* 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
def excel_fun(data):
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 :
sheetName=”My Sheet”
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
websites=[{"web":"http://najponude.com/","visits":10000},
{"web":"http://kako-napraviti.geek.hr/","visits":5000},
{"web":"http://hackspc.com","visits":8000}]
This function will export data from variable websites to excel file that looks like:
excel-data
This function can be your “template” code for exporting data in excel. Function as argumentaccept 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/
source: hackspc.com

Share this:

 
Copyright © 2014 MTT. Designed by OddThemes | Distributed By Gooyaabi Templates