你能教我 Python 是否可以写入同一个 Excel 文件,但可以写入 2 个不同的电子表格(选项卡)?
举个例子,我想把下面4个网站的标题挑出来写到同一个文件title.xls中,但是分别写在它的Sheet1和Sheet2中。
www.dailynews.com
www.dailynews.co.zw
www.gulf-daily-news.com
www.dailynews.gov.bw
Run Code Online (Sandbox Code Playgroud)
我用 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")
Run Code Online (Sandbox Code Playgroud)
但是,脚本正在覆盖工作表。我只能拥有 Sheet1 或 Sheet2,但不能同时拥有。
有帮助吗?谢谢。
您也可以使用熊猫来做到这一点。
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')
Run Code Online (Sandbox Code Playgroud)
小智 4
如果我正确理解你需要什么。抱歉,无法发表评论以使其更清楚。
sheet1 = book.add_sheet('Sheet1', cell_overwrite_ok = True)
sheet2 = book.add_sheet('Sheet2', cell_overwrite_ok = True)
sheet1.write (cor, 0, site_title[0].text)
sheet2.write (cor, 0, site_title[0].text)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15567 次 |
| 最近记录: |