【问题标题】:Adding data from different data frame to excel将不同数据框中的数据添加到excel
【发布时间】:2021-10-06 03:28:01
【问题描述】:

目前我想做的是从数据框列表中获取数据,并将它们作为自己的选项卡添加到现有的 excel 文件中。

为了测试这一点,我用一个数据框进行了尝试。没有错误,但是当我打开excel文件时,它说它已损坏。我继续恢复信息,但我宁愿不必每次都这样做。我相信如果我遍历我的列表来实现这一点,它会失败。

    import os,glob
    import pandas as pd
    from openpyxl import load_workbook
     
    master_file='combined_csv.xlsx'
    #set the directory
    os.chdir(r'C:\Users\test') 
    #set the type of file
    extension = 'csv' 
    #take all files with the csv extension into an array
    all_filenames = [i for i in glob.glob('*.{}'.format(extension))]
    col_to_keep=["Name",
                 "Area (ft)",
                 "Length (ft)",
                 "Center (ft)",
                 "ID",
                 "SyncID"]
        
    combine_csv = pd.concat([pd.read_csv(f, delimiter=';', usecols=col_to_keep) for f in all_filenames])
    combine_csv.to_excel(master_file, index=False,sheet_name='All')
    # Defining the path which excel needs to be created
    # There must be a pre-existing excel sheet which can be updated
    FilePath = r'C:\Users\test'
     
    # Generating workbook
    ExcelWorkbook = load_workbook(FilePath)
     
    # Generating the writer engine
    writer = pd.ExcelWriter(FilePath, engine = 'openpyxl')
     
    # Assigning the workbook to the writer engine
    writer.book = ExcelWorkbook
     
     
    # Creating first dataframe
    drip_file = pd.read_csv(all_filenames[0], delimiter = ';', usecols=col_to_keep)
    SimpleDataFrame1=pd.DataFrame(data=drip_file)
    print(SimpleDataFrame1)
     
     
    # Adding the DataFrames to the excel as a new sheet
    SimpleDataFrame1.to_excel(writer, sheet_name = 'Drip')
    
    writer.save()
    writer.close()

它似乎运行良好,没有错误,但是当我打开 excel 文件时,我得到如下所示的错误。

有没有人发现代码有问题会导致 excel 给我这个错误?

提前谢谢你

【问题讨论】:

    标签: python excel pandas dataframe openpyxl


    【解决方案1】:

    您的代码知道它的打印数据到同一个工作簿,但是要使用 writer,您还需要告诉 python 工作表名称是什么:

    book = load_workbook(your_destination_file)
    writer = pd.ExcelWriter(your_destination_file, engine='openpyxl')
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)  # tells 
    pandas/python what the sheet names are
    
    Your_dataframe.to_excel(writer, sheet_name=DesiredSheetname)
    
    writer.save()
    

    此外,如果您在文档中有透视图、图片、外部连接,它们将被删除,并且可能是导致损坏的原因。

    【讨论】:

    • 我并没有完全理解这里正在做什么。如果工作表名称尚不存在,我对 python 为什么或如何知道工作表名称感到有些困惑?我认为这条线是创建新表的原因。? Your_dataframe.to_excel(writer, sheet_name=DesiredSheetname)
    • 我明白了。在这种情况下,您的文件中可能有一些内容与 pandas 不兼容。除了您要插入的数据框之外,您的文件的内容是什么?
    • 感谢您的帮助!我更深入地研究了那条线,它告诉 panda/python 工作表名称是什么,并且能够通过首先创建将所有数据连接到第一张工作表中的文件并使用它来制作我的所有单独工作表来使其工作需要。再次感谢!
    • 不客气 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 2017-09-16
    • 2013-11-18
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多