【问题标题】:Modifying an excel sheet in a excel book with pandas用熊猫修改excel书中的excel表
【发布时间】:2020-11-29 04:00:08
【问题描述】:

对于在包含多个工作表的 excel 文件中修改现有工作表的问题,有一些建议的解决方案: How to save a new sheet in an existing excel file, using Pandas?https://github.com/pandas-dev/pandas/issues/3441,但所提出的解决方案都没有实际工作。他们要么添加额外的表替换所有其他表。我已经制作了下面的函数来解决问题,但它是非常迂回且非常糟糕的解决问题的方法。关于如何更好地做到这一点有什么想法吗?

def modify_sheet(file_name,sheet_to_change,new_sheet):
    """Add or modify sheets in an excel book

    Args:
        file_name (str): Name of the xlsx file
        sheet_to_change (str): Name of the sheet in question
        new_sheet (pd.DataFrame): The new dataframe
    """
    with pd.ExcelWriter(file_name, engine='xlsxwriter') as writer:
        df = pd.read_excel(file_name, sheetname=None, header=None, skiprows=0)
        if sheet_to_change not in df.keys():
            keys = list(df.keys())
            keys.append(sheet_to_change)
        else:
            keys = df.keys()  

        for key in keys:
            if sheet_to_change == key:
                new_sheet.to_excel(writer, sheet_name=str(key), header= False, index =False)
            else:
                df[key].to_excel(writer, sheet_name=str(key), header= False, index =False)

        writer.close()
        writer.save()


file_name = "blub.xlsx"
sheet_to_change = 'DKSheet1'
new_sheet = pd.DataFrame(np.random.rand(20,6))
modify_sheet(file_name,sheet_to_change,new_sheet)

【问题讨论】:

  • 您要完全替换一张纸,保留其他纸,还是更改一张纸中的某些行/单元格,保留所有其他纸?
  • 你可能想检查this solution
  • @MaxU 是的,作为第一步,用另一个数据框的内容替换一张纸就足够了。您链接到的答案解决了一个相关问题,我建议的代码也可以通过为工作表指定一个新名称来解决该问题。但我相信应该有一种更有效的方法来解决这个问题。如果没有人知道如何解决问题,可能值得提出问题。

标签: excel pandas


【解决方案1】:

在已经存在多张工作簿的工作表中,可以使用xlwings插入用pandas修改过的工作表。请参阅以下示例。首先,使用 .clear() 清除特定的工作表,然后将修改后的数据框插入到该工作表中。

import xlwings as xw
import pandas as pd

filename = "test.xlsx"

df = pd.read_excel(filename, "SheetX")

# Do your modifications of the worksheet here. For example, the following line "df * 2".
df = df * 2 

app = xw.App(visible=False)
wb = xw.Book(filename)
ws = wb.sheets["SheetX"]

ws.clear()

# This is the important line here, which inserts the dataframe to the particular worksheet.
ws["A1"].options(pd.DataFrame, header=1, index=False, expand='table').value = df

# If formatting of column names and index is needed as xlsxwriter does it, the following lines will do it (if the dataframe is not multiindex).
ws["A1"].expand("right").api.Font.Bold = True
ws["A1"].expand("down").api.Font.Bold = True
ws["A1"].expand("right").api.Borders.Weight = 2
ws["A1"].expand("down").api.Borders.Weight = 2

wb.save(filename)
app.quit()

【讨论】:

    猜你喜欢
    • 2021-08-19
    • 2018-10-05
    • 2015-06-10
    • 2019-03-21
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 2021-08-02
    相关资源
    最近更新 更多