Bi7n
Bi7n

Reputation: 55

How to use openpyxl to modify data in specific sheet in python

I am currently using openpyxl library to modify data in excel. My excel has many sheets and I could do it for the first sheet. However, when I was trying to modify the another one, it doesn't work and will destroy the file(I cant open the excel again.)

Here is how I do for first sheet,

from openpyxl import load_workbook;
book = load_workbook('Template.xlsx')
sheet = book.active #active means get the first sheet
sheet['A1']= 100
book.save('Template.xlsx')

However, it doesn't work for another one

sheet2 = book.get_sheet_by_name('Table 2')
sheet2['F9'] = 100
book.save('Template.xlsx')

The AttributeError: 'NoneType' object has no attribute 'read'

Explanation: get_sheet_by_name is not identical to get_sheet_name in the another question.

Anyone knows how to fix this? Thanks a mil!

Upvotes: 2

Views: 15498

Answers (1)

Riverman
Riverman

Reputation: 523

You're very close to the solution actually. This is good so far:

from openpyxl import load_workbook
book = load_workbook('Template.xlsx')
sheet = book.active #active means last opened sheet
sheet['A1']= 100
book.save('Template.xlsx')

To change to another sheet, you need to call it by its name:

sheet2 = book['Sheet 2']
sheet2['F9'] = 100
book.save('Template.xlsx')

Upvotes: 6

Related Questions