0

I have some rudimentary knowledge of openpyxl and having some issues here. I want to write some data (say "qwerty") to cell D4 of Sheet1 and "abcd" to cell "P7" of sheet 2. The workbook and the sheets do exist already. This is my code snippet:

from openpyxl import Workbook
excel = openpyxl.load_workbook('pqr.xlsx',read_only=False)
Sheet1 = excel.active
Sheet1['D4'] = 'qwerty'
#excel.save('pqr.xlsx')
Sheet2 = excel.active
Sheet2['P7'] = 'abcd'
excel.save('pqr.xlsx')

However, it ends up writing both the data on the Sheet1 cells only. Any help would be greatly appreciated. Thanks, Swanand.

Swanand
  • 1
  • 1
  • 1
  • Possible duplicate of [Python openpyxl select sheet](https://stackoverflow.com/questions/36814050/python-openpyxl-select-sheet) – Aran-Fey Apr 17 '18 at 23:42
  • This information is covered [in the tutorial](http://openpyxl.readthedocs.io/en/latest/tutorial.html). – chb Apr 18 '18 at 00:38

1 Answers1

0

Sheet names are stored as strings. You can refer each sheet name with the excel workbook object and set a value to a particular cell in that sheet.

import openpyxl

excel = openpyxl.load_workbook('test.xlsx')

excel.sheetnames   ['Sheet1','Sheet2']

excel['Sheet1']['A3'] = "Test1"

print(excel['Sheet1']['A3'].value)  #'Test1'

excel['Sheet2']['B5'] = "Test2"

print(excel['Sheet2']['B5'].value) #'Test2'
amanb
  • 5,276
  • 3
  • 19
  • 38