Writing resutls into 2 different sheets in the same Excel file

陌路散爱 提交于 2019-12-04 16:46:14

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)

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