83

I am writing some data into an Excel file, but I don’t know how to adjust the code in order to be able to control which sheet I am writing into:

from openpyxl import load_workbook

wb = load_workbook(filename)
active_ws = wb.active

Instead of wb.active, how can I say something like Sheets('Data') (this is how the VBA syntax would look like...)?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
horace_vr
  • 3,026
  • 6
  • 26
  • 48

4 Answers4

159

You should use wb[sheetname]

from openpyxl import load_workbook
wb2 = load_workbook('test.xlsx')
ws4 = wb2["New Title"]

PS: You should check if your sheet in sheet names wb.sheetnames

print(wb2.sheetnames)
['Sheet2', 'New Title', 'Sheet1']
Charlie Clark
  • 18,477
  • 4
  • 49
  • 55
Valeriy Solovyov
  • 5,384
  • 3
  • 27
  • 45
15
import openpyxl

n = 0
wb = openpyxl.load_workbook('D:\excel.xlsx')
sheets = wb.sheetnames
ws = wb[sheets[n]]

The reference: How to switch between sheets in Excel openpyxl Python to make changes

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Youssri Abo Elseod
  • 671
  • 1
  • 9
  • 23
1

Fix your openpyxl version. Upgrading from 2.3.2 to 2.4.10 will fix this issue. Do this:

pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org openpyxl==2.4.10
cottontail
  • 10,268
  • 18
  • 50
  • 51
0

The above solution works but just to point out that the excel file should be "Excel Workbook (.xlsx)" and not the "Strict Open XML Spreadsheet (.xlsx)"

workbook = openpyxl.load_workbook(file.xlsx)
sheet = workbook[sheet_name]
Neel
  • 33
  • 4