Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing resutls into 2 different sheets in the same Excel file

Tags:

python

xlwt

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.

like image 944
Mark K Avatar asked Dec 15 '22 20:12

Mark K


1 Answers

You can also do it using 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()
like image 124
Susa Avatar answered Apr 09 '23 08:04

Susa