Lets try to create Excel Files using python. There is a Addon for python named pyExcelerator. First you have to install it. Thats easy just go to http://sourceforge.net/projects/pyexcelerator
download pyExcelerator. Unpack it any where. Point folder from terminal as root. then
python setup.py build then type python setup.py install
Now here is a simple code to create an excel file of a table of MySQL database.
To connect with MySQL you need MySQL python its easy to install search google for installing MySQL Python.
My objective is to show you an easy code to create Excel file using python.
The code is given below:
__rev_id__ = """$Id: blanks.py,v 1.2 2005/07/22 08:22:26 rvk Exp $"""
#importing is done here
from pyExcelerator import *
import sys
import MySQLdb
#get data from mysql
table_name = "tareqfolder" #change the table name to the table name from which you want to create xls
sql_select="SELECT * FROM %s"%table_name
conn1 = MySQLdb.connect(host='host_name',user='mysql_user',passwd='secret_passwd',db='database_name') #connection information(change according to your mysql server)
cu_select=conn1.cursor(MySQLdb.cursors.DictCursor)
try:
cu_select.execute(sql_select)except MySQLdb.Error, e:
errInsertSql = "Insert Sql ERROR!! sql is==>%s" %(sql_select)
sys.exit(errInsertSql)result_set = cu_select.fetchall()
#creation of excel file starts here
wb = Workbook()
ws0 = wb.add_sheet('0')
borders = Borders()
borders.left = 1
borders.right = 1
borders.top = 1
borders.bottom = 1
borders_cell = Borders()
borders_cell.right = 1
TestNoPat = Pattern()
TestNoPat.pattern = Pattern.SOLID_PATTERN
TestNoPat.pattern_fore_colour = 0x07
Alg = Alignment()
Alg.horz = Alignment.HORZ_CENTER
Alg.vert = Alignment.VERT_CENTER
row_number=1
for row in result_set:
i=0
for item in row: val=str(row[item])
if row_number==1:
style = XFStyle()
style.borders = borders
style.pattern = TestNoPat
style.alignment = Alg
ws0.write(0,i,'', style)
ws0.write(0,i,item, style)
style = XFStyle()
style.borders = borders_cell
ws0.write(row_number,i,val, style)
i= i+1 else:
style = XFStyle()
style.borders = borders_cell
ws0.write(row_number,i,val, style)
i=i+1 row_number=row_number+1
wb.save('%s.xls'%table_name)
#xcel file created
print "SUCCESSFUL see in the directory a %s.xls is created "%table_name