Sunday, December 29, 2013

Some Generic Functions

#################### Start of the Program

#!/usr/bin/python

import csv
import xlwt
import xlrd
import sys
import urllib2
import json

1) Convert csv file from excel file
excel_file -- Excel file name which you want to convert
sheet_name -- Name of the sheet mention in Excel file which you want to convert
csv_file -- Csv filename for which you are converting from excel file.

This is generic funtion to convert data from excel file to csv file which you can use for wider purpose and no matters about amount of data.

def csv_from_excel(excel_file,sheet_name,csv_file):
    wb = xlrd.open_workbook(excel_file)
    sh = wb.sheet_by_name(sheet_name)
    your_csv_file = open(csv_file, 'wb')
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
    for rownum in xrange(sh.nrows):
        wr.writerow(sh.row_values(rownum))
    your_csv_file.close()

2) Code to change excel font in excel file 
clr_index -- This is generic color indexex to change color font

def excel_font(clr_index):
    font0 = xlwt.Font()
    font0.name = 'Times New Roman'
    font0.colour_index = clr_index
    font0.height=240
    font0.bold = True
    style0 = xlwt.XFStyle()
    style0.font = font0
    return style0

3) Code for bold font
def bold_font():
    style = xlwt.easyxf('font: bold 1, height 240')
    return style

4) Code for font height
def font_height():
    style = xlwt.easyxf('font: height 240')
    return style

5) Code to get column parameters from excel file
col_index -- Column Index from which you want to get parameters given in excel file. 

def get_column_params(excel_file,sheet_index,col_index):
    workbook = xlrd.open_workbook(excel_file)
    sheet = workbook.sheet_by_index(sheet_index)
    data = sheet.col_values(col_index,start_rowx=1)
    return data

6) Convert values from csv file to dictionary (data structure in python)
def csv_to_dict_params(csv_file,excel_file,len_of_sheets):
    d_parameters={}
    data=get_column_params(excel_file,len_of_sheets,1)
    column_len=len(data)
    with open(csv_file, 'rb') as f:
        rows = list(csv.reader(f))
        while column_len !=0:
            d_parameters[rows[column_len][1]]=rows[column_len][2]
            column_len=column_len - 1
    return d_parameters

7) Convert values from coming json to dictionary (as mentioned earlier,  (key,value) pair)
request_url -- url which returning json

def json_to_dict(request_url):
    req=urllib2.Request(request_url)
    response=urllib2.urlopen(req)
    full_resp=response.read()
    json_dict={}
    json_list=json.loads(full_resp)
    if type(json_list) is list and len(json_list)>0:
        temp_dict=json_list[0]
        for k,v in temp_dict.items():
            if type(v) is not dict:
                json_dict[k]=v
            else:
                for d_k,d_v in v.items():
                    json_dict[d_k]=d_v
    elif type(json_list) is dict and len(json_list)>0:
        for k,v in json_list.items():
            if type(v) is not list:
                json_dict[k]=v
            elif len(v)>0:
                json_dict[k]=""
                temp_dict=v[0]
                if type(temp_dict) is dict:
                    for k,v in temp_dict.items():
                        json_dict[k]=v
    return json_dict

########################## End of the Program

Examples Reading Excel (.xls) Documents Using Python's xlrd

If running Ubuntu, you can install Python's xlrd module by running the command:
I suppose you have already installed python in your system.
If xlrd module is not installed in your system.
you can easily install by command :
sudo easy_install xlrd

Open an Excel workbook:
import xlrd
workbook = xlrd.open_workbook('my_workbook.xls')

Grab list of worksheets in a workbook:
import xlrd
workbook = xlrd.open_workbook('my_workbook.xls')
print workbook.sheet_names()

Grab a specific worksheet from a workbook:
import xlrd
workbook = xlrd.open_workbook('my_workbook.xls')
worksheet = workbook.sheet_by_name('Sheet1')

Iterate over each worksheet in a workbook:
import xlrd
workbook = xlrd.open_workbook('my_workbook.xls')
worksheets = workbook.sheet_names()
for worksheet_name in worksheets:
    worksheet = workbook.sheet_by_name(worksheet_name)
    print worksheet

Iterate over each row of a worksheet:
import xlrd
workbook = xlrd.open_workbook('my_workbook.xls')
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
curr_row = -1
while curr_row < num_rows:
    curr_row += 1
    row = worksheet.row(curr_row)
    print row

Grab the cell contents of each row of a worksheet:
import xlrd
workbook = xlrd.open_workbook('my_workbook.xls')
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
num_cells = worksheet.ncols - 1
curr_row = -1
while curr_row < num_rows:
    curr_row += 1
    row = worksheet.row(curr_row)
    print 'Row:', curr_row
    curr_cell = -1
    while curr_cell < num_cells:
        curr_cell += 1
        # Cell Types: 0=Empty, 1=Text, 2=Number, 3=Date, 4=Boolean, 5=Error, 6=Blank
        cell_type = worksheet.cell_type(curr_row, curr_cell)
        cell_value = worksheet.cell_value(curr_row, curr_cell)
        print '    ', cell_type, ':', cell_value

My Profile

My photo
can be reached at 09916017317