簡體   English   中英

使用 openpyxl 模塊將值復制到 excel 工作表

[英]Copying values to an excel sheet using openpyxl module

我正在嘗試將我剛剛用湯刮掉的一堆標題復制到 excel 表中。 有 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 循環和 append 之外聲明一個數組以列出。

例如:

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

如果你有一個數組並且你想 append 它作為單行(到 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.

(您的代碼不可運行。因此我沒有測試上面的示例,但應該足以作為說明)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM