使用 openpyxl 模块将值复制到 excel sheet

Copying values to an excel sheet using openpyxl module

我正在尝试将我刚刚使用 soup 抓取的一堆标题复制到 excel sheet。有 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')

该练习需要专门使用 openpyxl 而不是 csv、pandas、win32com.client、xlrd、xlsxwriter 或其他方式。谢谢你的时间。

all_titles = title.find("h3", class_ = "k-item__title") - 代码在循环内分配一个变量。因此,这将始终包含 1 个项目。在保存到工作表时,它将包含最后一项。

考虑在 for 循环外声明一个数组并追加到列表中。

例如:

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())

如果你有一个数组并且你想将它作为单行追加(到 Excel),那么你可以调用 append()

例如:

替换此代码:

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

有:

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.

(您的代码不可运行。因此我没有测试上面的示例,但作为说明应该足够好了)