Writing resutls into 2 different sheets in the same Excel file

天大地大妈咪最大 提交于 2019-12-09 20:50:43

问题


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.


回答1:


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)



回答2:


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



回答3:


import numpy as np 
import pandas as pd

# Create a Dataframe
df1 = pd.DataFrame(np.random.rand(100).reshape(50,2),columns=['a','b'])
df2 = pd.DataFrame(np.random.rand(100).reshape(50,2),columns=['a','b'])

# Excel path
excelpath = 'path_to_your_excel.xlsx'

# Write your dataframes to difference sheets

with pd.ExcelWriter(excelpath) as writer:
    df1.to_excel(writer,sheet_name='Sheet1')
    df2.to_excel(writer,sheet_name = 'Sheet2')


""" I noticed that the above script overwrite all existing columns of in 
the excel. In case you want to keep some columns and sheet untouched, 
you might consider doing it the following way"""

import pandas as pd
import numpy as np
from openpyxl import load_workbook

book = load_workbook(excelpath)
writer = pandas.ExcelWriter(excelpath, engine='openpyxl') 
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

df1.to_excel(writer, "Sheet1", columns=['a', 'b']) # only columns 'a' and 'b' will be populated 
df2.to_excel(writer,"Sheet2",columns=['a','b']) # only columns 'a' and 'b' will be populated 

writer.save()


来源:https://stackoverflow.com/questions/25199507/writing-resutls-into-2-different-sheets-in-the-same-excel-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!