将结果写入同一 Excel 文件中的 2 个不同工作表中

2024-03-20

你能教我Python是否可以写入同一个Excel文件,但2个不同的电子表格(选项卡)?

举例来说,我想挑选并写入以下4个网站的标题,并将它们写入同一个文件title.xls中,但分别写入其Sheet1和Sheet 2中。

www.dailynews.com
www.dailynews.co.zw
www.gulf-daily-news.com
www.dailynews.gov.bw

我用 2 个脚本执行这些操作,每个脚本针对 2 个网站:

from bs4 import BeautifulSoup
import urllib2
import xlwt

line_in_list = ['www.dailynews.com','www.dailynews.co.zw'] 
# line_in_list = [www.gulf-daily-news.com','www.dailynews.gov.bw']

book = xlwt.Workbook(encoding='utf-8', style_compression = 0)
sheet = book.add_sheet('Sheet1', cell_overwrite_ok = True) 
# sheet = book.add_sheet('Sheet2', cell_overwrite_ok = True)

for cor,websites in enumerate(line_in_list):
    url = "http://" + websites
    page = urllib2.urlopen(url)
    soup = BeautifulSoup(page.read())
    site_title = soup.find_all("title")
    print site_title
    sheet.write (cor, 0, site_title[0].text)

book.save("title.xls")

但是,脚本正在覆盖工作表。我只能拥有 Sheet1 或 Sheet2,但不能同时拥有两者。

有什么帮助吗?谢谢。


您也可以使用 pandas 来完成此操作。

import pandas as pd

# Add your data in list, which may contain a dictionary with the name of the      
# columns as the key
df1 = pd.DataFrame({'website': ['www.dailynews.com', 'www.dailynews.co.zw']})
df2 = pd.DataFrame({'website': ['www.gulf-daily-news.com', 'www.dailynews.gov.bw']})

# Create a new excel workbook
writer = pd.ExcelWriter('title.xlsx', engine='xlsxwriter')

# Write each dataframe to a different worksheet.
df1.to_excel(writer, sheet_name='Sheet1')
df2.to_excel(writer, sheet_name='Sheet2')

# Save workbook
writer.close()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将结果写入同一 Excel 文件中的 2 个不同工作表中 的相关文章

随机推荐