How do I automatically generate sheets using openpyxl in python?

Asked 2 years ago, Updated 2 years ago, 82 views

import openpyxl:
# You must create an empty excel file named sample.xlsx in the same folder as the py file.
excel_document = openpyxl.load_workbook('same.xlsx')

sheet1 = excel_document.get_sheet_by_name('TEST')


initSet = ['0.1','0.2','0.3','0.4']

#list = [[0.139485297,0.2,0.3],[0.1,0.3,0.6],[0.2,1.4,0.3],[1.6,1.4,1.5,1,1,1,1,1]]

list = ["X", "Alpha", "Beta", "Gamma", "B/A", "C/A", "C/B"]


A =[0.3,0.5,0.7,0.4,0.2]
B =[0.1,0.3,0.5,0.7,0.9]
C =[0.1,0.4,0.2,0.1,0.5]

for i in range(0,len(list)):
    sheet1.cell(i+1,1).value = list[i]

for i in range(0,len(initSet)):
    sheet1.cell(1,i+2).value = initSet[i]
for i in range(0,len(A)):
    sheet1.cell(2,i+2).value = A[i]
for i in range(0,len(B)):
    sheet1.cell(3,i+2).value = B[i]
for i in range(0,len(C)):
    sheet1.cell(4,i+2).value = C[i]

excel_document.save("TEST.xlsx")
excel_document.close()

It's my current code, and if I make it, one sheet will be made. All I want is

I'd like to make several sheets using for statements like this.

Can we know how

?

openpyxl excel

2022-09-22 14:06

1 Answers

Please refer to the sample below.

>>> from openpyxl import Workbook
>>> wb = Workbook()
>>> sheets = [wb.create_sheet(title = 'Sheet{}'.format(n)) for n in range(1, 5)]
>>> sheets
[<Worksheet "Sheet1">,
 <Worksheet "Sheet2">,
 <Worksheet "Sheet3">,
 <Worksheet "Sheet4">]


2022-09-22 14:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.