Wednesday 18 October 2017

Writing dynamic data to excel sheet using python

"""writing dynamic data to excel sheet using ordered dictionaries generating continuous Name tags in the excel sheet based on name and dynamic values"""
import xlwt
from collections import OrderedDict


def push_data_to_excel():
    book = xlwt.Workbook(encoding="utf-8")
    sheet1 = book.add_sheet("Device_Details")
    list1 = ["Tag Name", "parameter_name", "state", "results"]
    for i,j in enumerate(list1):
        sheet1.write(0, i, j)
    book.save("trial.xls")
    return sheet1, book


def create_tag():
    sheet_obj, book = push_data_to_excel()
    c = 1
    tag_name = "Narendra"
    state = "R/W"
    parameter_name = "coil_1"
    results = (1, 0, 1, 1, 0, 0, 1,0,1,1,1)
    if len(results)>0:
        dict1 = OrderedDict()
        i = 1
        for val in results:
            # creating dictionary for keys(tag names) & corresponding values(1,0,1,1,0,0,...)
            t_name = tag_name + '_' + str(i)
            dict1[t_name] = val
            i += 1
            print(dict1.keys())

        for m, n in dict1.items():
            sheet_obj.write(c,0, m)
            sheet_obj.write(c, 1, parameter_name)
            sheet_obj.write(c, 2, state)
            sheet_obj.write(c, 3, n)
            c += 1
            book.save("trial.xls")

create_tag()

                                Request: Please provide your valuable comments