简体   繁体   中英

Write onto multiple sheets in the same excel file using openpyxl

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM