Taimur
Taimur

Reputation: 39

Excelsheet in xlsxwriter

I want to create a workbook and worksheet once using xlsxwriter outside my function, as I am calling my function from a robot framework to insert the items in excel.

However, my code gives me an error.

class writetoexcel:


    workbook = xlsxwriter.Workbook('Example2.xlsx')
    worksheet = workbook.add_worksheet()

    def my_func(self, value, count):
        print(value)

        row = 0
        column = 1
        # worksheet.write_string(row, column, value)

        for item in value:
            worksheet.write_string(row, column, item)
            worksheet.write_string(row, column, item)

            row += 1

        workbook.close()

Upvotes: 0

Views: 55

Answers (1)

Dimitris Thomas
Dimitris Thomas

Reputation: 1393

You are getting an error because you are trying to initiate the xlsxwriter outside of the function or of the init method. This is your corrected code:

import xlsxwriter

class writetoexcel:

    def my_func(self, value):
        workbook = xlsxwriter.Workbook('Example2.xlsx')
        worksheet = workbook.add_worksheet()

        print(value)
        row = 0
        column = 1

        for item in value:
            worksheet.write_string(row, column, item)
            row += 1

        workbook.close()

Then you need to create an object:

myworkbook = writetoexcel()

And finally call its method we created:

myworkbook.my_func('abcd')

Output:

enter image description here

Finally i think this code is a better approach if you want to handle the workbooks as objects:

class writetoexcel:

    def __init__(self):
        self.workbook = xlsxwriter.Workbook('Example2.xlsx')
        self.worksheet = self.workbook.add_worksheet()

    def my_func(self, value):
        row = 0
        column = 1

        for item in value:
            self.worksheet.write_string(row, column, item)
            row += 1

        self.workbook.close()

Upvotes: 2

Related Questions