[英]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. 我必须编写一个非常烦人的脚本,使用一个excel文件来更新另一个,但因为你不能直接编辑xls文件,也不能插入行,我不得不即兴创作。
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? 现在我的问题是:使用xlwt模块进行Python(使用2.7x),当您创建工作簿并正在处理它时,如何写入在不同函数中创建的同一工作表? 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]?
如果是这样,我如何访问我制作的第一个工作表,工作簿[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. 我有多个函数需要与我正在制作的xlwt xls文件进行交互,所以我只想确保我可以将它传递给不同的函数。
Thanks! 谢谢!
...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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.