简体   繁体   English

使用 openpyxl 模块将值复制到 excel 工作表

[英]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.我正在尝试将我刚刚用汤刮掉的一堆标题复制到 excel 表中。 There are 100 titles and I would like to copy all of them in the first column from A1:A100 using openpyxl.有 100 个标题,我想使用 openpyxl 从 A1:A100 的第一列中复制所有标题。

#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.练习需要专门使用 openpyxl 而不是 csv、pandas、win32com.client、xlrd、xlsxwriter 或其他方式。 Thank you for your time.感谢您的时间。

all_titles = title.find("h3", class_ = "k-item__title") - The code is assigning a variable inside loop. all_titles = title.find("h3", class_ = "k-item__title") - 代码在循环内分配一个变量。 As a result this will always contain 1 item.因此,这将始终包含 1 个项目。 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 循环和 append 之外声明一个数组以列出。

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()如果你有一个数组并且你想 append 它作为单行(到 Excel),那么你可以调用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) (您的代码不可运行。因此我没有测试上面的示例,但应该足以作为说明)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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