Python 使用openpyxl模块将值复制到excel工作表
我正试图把我刚刚用soup拼凑的一堆标题复制到excel表格中。共有100个标题,我想使用openpyxl从A1:A100复制第一列中的所有标题Python 使用openpyxl模块将值复制到excel工作表,python,openpyxl,Python,Openpyxl,我正试图把我刚刚用soup拼凑的一堆标题复制到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_= "
#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\u titles=title.find(“h3”,class=“k-item\uu 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()
例如:
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())
替换此代码:
for i in range("A1:A100"):
ws[i] = all_titles
与:
(您的代码无法运行。因此,我没有测试上面的示例,但应该足以作为一个示例)感谢您的回答。它会在A1到……之间的列中追加所有标题。BF1是否有解决方案可以在A1到A100之间的行中追加标题?我已经更新了答案。您只需要使用双括号ws.append((所有标题))