How to put values in cells in multiple sheets in Python Excel?

Asked 1 years ago, Updated 1 years ago, 111 views

import openpyxl

wb = openpyxl.Workbook('part1.xlsx')

for i in range(0,10):
    sheets = wb.create_sheet('sheet%d'%(i),i)

s = []
for i in range(0,10):
    s.append('sheet%d'%(i))

list = ["X", "Alpha", "Beta", "Gamma", "B/A", "C/A", "C/B"]
initSet = ['0.1', '0.2', '0.3', '0.4']
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]
Sheet1 = wb.get_sheet_by_name('TEST') # I want to change this part and put the list value in several sheets
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]

wb.save('sam.xlxs')

Creating Excel file with python. That's the code I've done so far. If I do it up to here,

Multiple sheets can be created, and the for statement below can only be used to put the value in one sheet.

What I want is to put the value in each sheet, is there a way?

I made s=[ ] because I thought it would be possible to make it using the same sheet name.

python3.7 excel openpyxl sheet

2022-09-22 19:14

1 Answers

Please refer to the example below.

from openpyxl import Workbook

wb = Workbook()
sheets = [wb.create_sheet(title = 'Sheet{}'.format(n)) for in range(1,5)] # Create required sheet

for n in range(0, 4):
    sheets[n]['A1'] = n # Store n values in A1 cells from sheets 1 to 4

wb.save('test.xlsx')


2022-09-22 19:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.