热门标签:
Q:

Pandas dataframe到excel文件中的特定工作表,而不会丢失格式

我有一个像下面所示的dataframe

Date,cust,region,Abr,Number,         
12/01/2010,Company_Name,Somecity,Chi,36,
12/02/2010,Company_Name,Someothercity,Nyc,156,

df = pd.read_clipboard(sep=',')

我想将此dataframe写入文件output.xlsx中的特定工作表(称为temp_data)

因此,我尝试了以下内容

import pandas
from openpyxl import load_workbook

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

我也尝试了以下内容

path = 'output.xlsx'

with pd.ExcelWriter(path) as writer:
    writer.book = openpyxl.load_workbook(path)
    final_df.to_excel(writer, sheet_name='temp_data',startrow=10)
writer.save()

但我不确定我是否过于复杂。 我得到一个错误,如下所示。 但我在任务管理器中验证了它,没有excel文件/任务正在运行

BadZipFile:文件不是zip文件

此外,当我设法根据以下建议编写文件时,我也会丢失output.xlsx文件的格式。 我已经有一个整齐格式化的字体,颜色文件等,只需要把数据放在里面。

<img alt="在这里输入图像描述"src="https://i.stack.imgur.com/StART.png缧/>

是否有将pandas dataframe写入现有excel文件中的特定工作表? 而不会丢失DESTIATION文件的格式

原网址
A:

您只需使用pandas dataframe中的to_excel即可。

试试下面的片段:

df1.to_excel("output.xlsx",sheet_name='Sheet_name')

如果有现有的数据,请尝试下面的片段:

writer = pd.ExcelWriter('output.xlsx', engine='openpyxl')
# try to open an existing workbook
writer.book = load_workbook('output.xlsx')
df.to_excel(writer,index=False,header=False,startrow=len(reader)+1)
writer.save()
writer.close()

所有回答

共 2 条

author avatar

您是否仅限于使用pandas或openpyxl? 因为如果您喜欢使用其他库,最简单的方法可能是使用win32com来傀儡excel,就好像您是手动复制和粘贴信息的用户一样。

import pandas as pd
import io
import win32com.client as win32
import os

csv_text = """Date,cust,region,Abr,Number      
12/01/2010,Company_Name,Somecity,Chi,36
12/02/2010,Company_Name,Someothercity,Nyc,156"""



df = pd.read_csv(io.StringIO(csv_text),sep = ',')
temp_path = r"C:\Users\[User]\Desktop\temp.xlsx" #temporary location where to write this dataframe
df.to_excel(temp_path,index = False) #temporarily write this file to excel, change the output path as needed

excel = win32.Dispatch("Excel.Application")
excel.Visible = True #Switch these attributes to False if you'd prefer Excel to be invisible while excecuting this script
excel.ScreenUpdating = True 


temp_wb = excel.Workbooks.Open(temp_path)
temp_ws = temp_wb.Sheets("Sheet1")

output_path = r"C:\Users\[User]\Desktop\output.xlsx" #Path to your output excel file
output_wb = excel.Workbooks.Open(output_path)
output_ws = output_wb.Sheets("Output_sheet")

temp_ws.Range('A1').CurrentRegion.Copy(Destination = output_ws.Range('A1')) # Feel free to modify the Cell where you'd like the data to be copied to
input('Check that output looks like you expected\n') # Added pause here to make sure script doesn't overwrite your file before you've looked at the output

temp_wb.Close()
output_wb.Close(True) #Close output workbook and save changes
excel.Quit() #Close excel
os.remove(temp_path) #Delete temporary excel file

让我知道这是否达到了你所追求的。

author avatar

您的问题的解决方案存在于这里:如何在现有的excel文件中保存新工作表,使用Pandas?

从df添加新工作表:

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

os.chdir(r'C:\workdir')

path = 'output.xlsx'
book = load_workbook(path)
writer = pd.ExcelWriter(path, engine = 'openpyxl')
writer.book = book
### replace with your df ###
x = np.random.randn(100, 2)
df = pd.DataFrame(x)


df.to_excel(writer, sheet_name = 'x')
writer.save()
writer.close()

相似问题