Python Forum

Full Version: Unable to write to excel - Using openpyxl module
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there,

Trying to write simple class for writing data in to excel file.

first create workbook and saved to the given file name

   from openpyxl import Workbook()
   class Excel:
      wb = None
      ws = None
1)Initialize the excel file . Successfully create the excel file and managed to save to file location
def initexcel(self,sheet_name)
		wb = Workbook()
		ws = wb.create_sheet(sheet_name,0)
		wb.save(filename)
        return ws


Problem starting from this point
2) write data into excel file.
     def writeexcel(sheet_name, ro,col,data)
        ws = self.wb[sheet_name]             # trying to activate the sheet using the sheet name. N not working  
        ws.cell(column = col,row = ro, value = data #not working
What I need to do is to write data to excel file ( that have created using the first method initexcel). activate the sheet_name sheet and write data to cell ( ro,col)

Thanks in advance!
Appreciate any help Smile
In your writeexcel function/method, use
wb = ws.active
to specify the active workbook.

See https://openpyxl.readthedocs.io/en/stable/usage.html
Thanks for the reply!

I have tried it two different way

1) getting error
   def writeexcel(sheet_name,to,col,data)
       ws  = self.wb[sheet_name] #calling sheet by sheet_name
                                 #TypeError: 'NoneType' object is not subscriptable
       ws = self.active          #AttributeError:'NoneType' object has no attribute active 
2)second method not getting any error but it's not writing in to excel
  def writeexcel(self,wkb,sheet_name,to,col,data):
     print(wkb[sheet_name]) #<Worksheet 'sheet1'>
     ws =wkb[sheet_name]
     ws = wkb.active
     ws[’A1] = 'abc’ 
This method able to run without any error, but writing not happening