Michael M
Michael M

Reputation: 456

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

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!

Upvotes: 1

Views: 1906

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 113978

...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")

Upvotes: 3

Related Questions