pythonxlwt

Writing resutls into 2 different sheets in the same Excel file


can you teach me whether Python can write into a same Excel file, but 2 different spreadsheets (tabs)?

Just for example, I want to pick and write the titles of below 4 websites, and write them into the same file title.xls but respectively in its Sheet1 and Sheet 2.

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

I do them in 2 scripts, each for 2 websites:

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

however, the script is overwriting the sheets. I can only have either Sheet1 or Sheet2 but never both.

any helps? thanks.


Solution

  • If I correctly understood what you need. Sorry, can't comment to make it more clear.

    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)