简体   繁体   中英

Copying values to an excel sheet using openpyxl module

I'm trying to copy a bunch of titles I just scraped using soup to an excel sheet. There are 100 titles and I would like to copy all of them in the first column from A1:A100 using openpyxl.

#workbook already created in the same directory with python file
wb = openpyxl.load_workbook('Book1.xlsx') 
ws = wb.active

titles = soup.find_all("div", class_= "book-titles__info_clear")

for title in titles:
   all_titles = title.find("h3", class_ = "k-item__title")
   print(all_titles)
   #titles print fine in the console

for i in range("A1:A100"):
    ws[i] = all_titles
#this code only copies the last title in cell A2

wb.save('Book2.xlsx')

The exercise requires to specifically use openpyxl not csv, pandas, win32com.client, xlrd, xlsxwriter or other means. Thank you for your time.

all_titles = title.find("h3", class_ = "k-item__title") - The code is assigning a variable inside loop. As a result this will always contain 1 item. When it comes to saving to worksheet, it will contain the last item.

Consider declaring an array outside the for loop and append to list.

For example:

all_titles = []

for title in titles:
    h3 = title.find("h3", class_ = "k-item__title")
    if h3:
       all_titles.append(h3.text.strip())
       print(h3.text.strip())

If you have an array and you want to append it as a single row (to Excel), then you can call append()

For example:

Replace this code:

for i in range("A1:A100"):
    ws[i] = all_titles

With:

ws.append(all_titles) # if all_titles is an array then items will append to multiple rows.

ws.append((all_titles)) # double brackets will append list to entire row or you can change all_titles to contain a nested array.

(Your code is not runnable. Therefore I've not tested the example above, but should be good enough as an illustration)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM