将Pandas数据框添加到现有的Excel工作表中。

3
有没有办法将数据框架放入现有的Excel表格中。我有一个数据框架,需要将其复制到特定的Excel表格中的特定位置,即单元格A2,以便它可以镜像(粘贴)整个数据框架。从所选单元格开始(如图片所示),包括下面的单元格。这样,我就不必逐个分配值给特定的单元格了。
df = pd.DataFrame([[1,2,3],[1,2,3]], columns=list('ABC'))

enter image description here

enter image description here


为什么不使用CSV?CSV格式可以在Excel中打开。CSV是开源的。 - Joshua
5个回答

6
使用xlwings功能,它对我有效,可以保留所有数据和样式格式。
import xlwings as xw
import pandas as pd

#create DF
df = pd.DataFrame([[7,2,3],[1,2,3]], columns=list('ABC'))

#load workbook
app = xw.App(visible=False)
wb = xw.Book('doc.xlsx')  
ws = wb.sheets['Sheet1']

#Update workbook at specified range
ws.range('A2').options(index=False).value = df

#Close workbook
wb.save()
wb.close()
app.quit()

[结果]

将数据框复制到特定的 Excel 工作表 Sheet1 的特定位置单元格 A2,而不会丢失任何信息。在此示例中,图表会自动更新,引用 A2:C4

输入图像描述


由于某些原因,这个解决方案对于大型的pandas数据框不起作用。我收到了一个错误消息,提示进程已超时。 - FredMaster
不能确定在Linux上是否可能。我个人认为最好使用openpyxl来避免操作系统特定性。 - Vitalizzare

2
Pandas允许您将数据框写入Excel并指定要从哪一列和行开始。因此,在您的情况下,可以提及:
df.to_excel(writer, sheet_name='Sheet1', header=None, index=False,
         startcol=1, startrow=2)

需要相应地更新sheet_name


因此,您的整个代码可能如下所示:

import pandas as pd
from openpyxl import load_workbook

fn = r'C:\YourFolder\doc.xlsx'
book = load_workbook(fn)

df = pd.DataFrame([[1,2,3],[1,2,3]], columns=list('ABC'))

writer = pd.ExcelWriter(fn, engine='openpyxl')

writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

df.to_excel(writer, sheet_name='Sheet1', header=None, index=False,
             startcol=1, startrow=2)

writer.save()

我使用了你的代码,但是出现了一个AttributeError错误:无法设置属性'sheets'。可能是什么问题呢? - Tessa
这个github讨论谈到了这个问题。有一些已经被弃用的内容。不幸的是,我无法验证这个问题。请参考此链接,并随时更新答案,如果需要的话。 - Gangula

2

如何将数据写入现有的Excel工作簿中的任意位置

openpyxl 3.0.10 pandas 1.5.1

让我们来看看这个工作流程:

import pandas as pd
import openpyxl

# create a dummy data frame
df = pd.DataFrame({
    'one': [*'abcd'],
    'two': [*'wxyz'],
})

# write data into a new file
file_name = 'test_openpyxl.xlsx'
df.to_excel(file_name)

# NOTE: stop here and see the data in Excel,
#       close the file before continuing

# create a writer with parameters mode and if_sheet_exists
writer = pd.ExcelWriter(
    path=file_name,
    engine='openpyxl',
    mode='a',                   # append data to the file
    if_sheet_exists='overlay'   # keep previous data on existing sheets
)

# update data and write changes to the file
df['two'] = df['two'].str.upper()
df.to_excel(
    writer,                    # use openpyxl writer
    sheet_name='Sheet1',       # to update data on the existing sheet
    columns=['two'],           # in this only columns
    header=False,              # with no headers
    index=False,               # and no index printed
    startrow=1,                # at this specific position 
    startcol=2,                # with rows and cols numbering from 0
)    

writer.close()                 # file is saved by default when close

此方法在Linux和Windows上同样适用。请注意,xlsxwriter不支持追加模式,因此我们必须使用openpyxl来更新现有数据。最好避免同时在Python和Excel中处理同一个文件。

关键参数是if_sheet_existsmode='a',可以是以下之一:

  • error引发ValueError错误。
  • new创建一个新的工作表,其名称由引擎确定。
  • replace在写入之前删除工作表的内容。
  • overlay将内容写入现有工作表而不删除旧内容。

0

您可以检查给定的工作表是否存在,然后删除现有的工作表并添加一个新的。

import xlwings as xw
def df_to_excel_util(excel,sheet_to_dataFrame_map):

    with xw.App(visible=False) as app:
        wb = app.books.open(excel)            
        current_sheets = [sheet.name for sheet in wb.sheets]
        
        for sheet_name in sheet_to_dataFrame_map.keys():
            if sheet_name in  current_sheets:
                wb.sheets[sheet_name].delete()
            
            new_sheet = wb.sheets.add(after=wb.sheets.count)
            new_sheet.range('A1').value = sheet_to_dataFrame_map.get(sheet_name)
            new_sheet.name = sheet_name
        wb.save()

-1

你可以使用pd.read_excel()读取Excel文件,将第一行复制到你的DataFrame中,并将DataFrame保存为同名的Excel文件。


谢谢您的尝试。但是这会完全覆盖整个文件!! - AziMez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接