Home » excel » python – Can you use the same instance of a xlwt workbook in different functions?

python – Can you use the same instance of a xlwt workbook in different functions?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have to code a really annoying script that uses one excel file to update another, but because you cannot directly edit a xls file, nor insert row, I have had to improvise.

Now my question is:
Using the xlwt module for Python (using 2.7x), when you create a workbook and are working on it, how does one write to the same worksheet that was created in a different function? Can I just pass the workbook back and forth with its variable name? If so, how do I access the first worksheet I made, workbook[0]?

I have multiple functions that need to interact with this xlwt xls file I am making, so I just want to be sure I can pass it around different functions.

Thanks!

How to&Answers:

…yes

import xlwt
class MyWorkbook:
    ''' allow access to a workbooks sheets'''
    def __init__(self,*args,**kwargs):
        self.wb = xlwt.Workbook(*args,**kwargs)
        self.sheets = []
    def add_sheet(self,sheet_name):
        self.sheets.append(self.wb.add_sheet(sheet_name))
        return self.sheets[-1]
    def GetSheetByIndex(self,n):
        return self.sheets[n]
    def save(self,fname_or_stream):
        return self.wb.save(fname_or_stream)

def CreateWB():
    ''' return a MyWorkbook instance with 1 sheet'''
    m= MyWorkbook()
    m.add_sheet("first_sheet")
    return m
def ModifySheet0(mwb):
    '''uses instance of MyWorkbook and modifies sheet0'''
    s = mwb.GetSheetByIndex(0)
    s.write(0,0,"Hello World!")
def DoItAll()
    '''passing around MyWorkbook'''
    wb = CreateWB()
    ModifySheet0(wb)
    wb.save("somefile.xls")