Python - how to create spreadsheet in excel (with 100 columns)

Asked

Viewed 2,453 times

1

Good afternoon!

I already know how to create a spreadsheet in Excel by Python, when I know exactly which columns I need to create. But how can I make the creation of columns dynamic? for example:

to create a simple spreadsheet, I use the Workbook library and do so:

from openpyxl import Workbook

book = Workbook()
sheet = book.active
nome_xlsx = 'teste.xlsx'

sheet['A1'] = 'ID1'
sheet['B1'] = 'ID2'
sheet['C1'] = 'ID3'
sheet['D1'] = 'ID4'
sheet['E1'] = 'ID5'
lista_de_ordenacao = list(string.ascii_uppercase)
cont = 2
for item in lista_de_ordenacao:
    item1 = item[0]
    sheet['A'+str(cont)] = int(item1)
    item2 = item[1]
    sheet['B'+str(cont)] = str(item2)
    item3 = item[2]
    sheet['C'+str(cont)] = str(item3)
    item4 = item[3]
    sheet['D'+str(cont)] = str(item4)
    item5 = item[4]
    sheet['E'+str(cont)] = str(item5)
    cont = cont + 1

book.save(nome_xlsx)

But, as I would create for example, 100 columns so I don’t have to manually type in the code sheet['CV1'] = 'qualquer coisa'?

In my case, I need to make several spreadsheets with matrices, so some may have 100 rows and 100 columns, others may have 1000 rows and 1000 columns

This value varies according to the data I need to put in the matrix

Thank you for your attention!

1 answer

0


Solved! I don’t know if this was the best way to solve, but I was able to develop so:

from openpyxl import Workbook
import string

book = Workbook()
sheet = book.active
nome_xlsx = 'teste.xlsx'

listax=[]
abrir_aquivo = open('DADOS.txt', 'r' ,encoding='utf8')
lista_seguindo_usuario = abrir_aquivo.read()
listax = lista_seguindo_usuario.split('\n')
abrir_aquivo.close()
usuario_principal = listax[0]
del(listax[0])
numero_seguindo = int(listax[0])
del(listax[0])


lista = list(string.ascii_uppercase)
lista2 = list(string.ascii_uppercase)
lista2.insert(0,'A')
aux = 0
cont = 0
flag = 0
x=1
numero_seguindo = numero_seguindo + 1
while cont != numero_seguindo:
    print(cont)
    aux2 = lista2[0]
    if aux == (len(lista)):
        aux = 0
        flag = 1
        del(lista2[0])
        aux2 = lista2[0]
    if aux < len(lista)  and flag == 0:
        sheet[str(lista[aux]) + str(x)] = listax[0]
        aux = aux + 1
    if aux < len(lista) and flag == 1:
        sheet[aux2 + str(lista[aux]) + str(x)] = listax[0]
        aux = aux + 1
    cont = cont + 1
    sheet['A'+str(cont+1)] = listax[0]
    del(listax[0])    
sheet['A1'] = 'MATRIZ'



book.save(nome_xlsx)

PS:in the second line of txt has the number of columns and rows I need to do :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.