Python - ¿Cómo puedo escribir mi tabla de datos fila tras fila en Excel con xlsxwriter?

CorePress2024-01-25  11

Estoy teniendo problemas al iterar filas en xlsxwriter una vez más. Probé muchas combinaciones pero fallé. ¡Su ayuda será muy apreciada! Mi código;

file = open("namelist.txt","r")
data = []

for d in file:
    url = "file:///C:/Users/k/Desktop/HTML/"
    t = (url) + d
    data.append(t.strip())
file.close()

# data variable becomes --> ['file:///C:/Users/k/Desktop/HTML/new01.html', 'file:///C:/Users/k/Desktop/HTML/new02.html', 
# 'file:///C:/Users/k/Desktop/HTML/new03.html', 'file:///C:/Users/k/Desktop/HTML/new04.html']

workbook = xlsxwriter.Workbook("namelist.xlsx")
worksheet = workbook.add_worksheet("Name list")

# this peace of code writes header
for headers in data:
    b = data[0]
    browser.get(b)
    header = browser.find_elements_by_xpath("/html/body/table/tbody/tr[1]/th")
    head = []
    for h in header:
        head.append(h.text)
        worksheet.write_row("A1", head)

print ("Headers written to namelist.xlsx succesfully!")
print ("Given Name list being written to namelist.xlsx...")

# this part of the core overrites the tables to excel file
for i in data:
    browser.get(i)
    trs = browser.find_elements_by_xpath("/html/body/table/tbody/tr")
    for n, tr in enumerate(trs):
        row=[td.text for td in tr.find_elements_by_tag_name("td")]
        print (row)
        worksheet.write_row("A{}".format(1+n), row)
print ("namelist.xlsx is ready!")
workbook.close()

Cada enlace en datos[ ] contiene una tabla de datos diferentes con el mismo formato. Me gusta esto a continuación

El bucle For en mi código sobrescribe las filas, por lo que solo puedo ver una de las tablas anteriores en Excel

sin embargo, necesito que se escriban iterando en todos los enlaces y escribiendo fila tras fila de esta manera;

¡Muchas gracias de antemano!

Intenta usar worksheet.append insté.

- Arundeep Chohan

28 de marzo de 2021 a las 3:25

¿En lugar de worksheet.write_row?

- método

28/03/2021 a las 11:27



------------------------------------

Aparentemente tienes 1,2,3... valores en n en el último ciclo, crea alguna variable con int e incrementala en el ciclo como:

line = 1
for tr in trs:
    row=[td.text for td in tr.find_elements_by_tag_name("td")]
    print (row)
    worksheet.write_row("A{}".format(line + 1), row)
    line += 1

Su guía para un futuro mejor - libreflare
Su guía para un futuro mejor - libreflare