简体   繁体   English

无法将工作表添加到 Python 中的 xlsx 文件

[英]Unable to add worksheets to a xlsx file in Python

I am trying to export data by running dynamically generated SQLs and storing the data into dataframes which I eventually export into an excel sheet.我正在尝试通过运行动态生成的 SQL 并将数据存储到数据框中来导出数据,我最终将其导出到 excel 工作表中。 However, through I am able to generate the different results by successfully running the dynamic sqls, I am not able to export it into different worksheets within the same excel file.但是,通过成功运行动态 sql 能够生成不同的结果,但我无法将其导出到同一个 excel 文件中的不同工作表中。 It eventually overwrites the previous result with the last resultant data.它最终会用最后生成的数据覆盖先前的结果。

for func_name in df_data['FUNCTION_NAME']:
        sheet_name = func_name  
        sql = f"""select * from table({ev_dwh_name}.OVERDRAFT.""" + sheet_name + """())"""
        print(sql)                
        dft_tf_data = pd.read_sql(sql,sf_conn)
        print('dft_tf_data')  
        print(dft_tf_data)
        # dft.to_excel(writer, sheet_name=sheet_name, index=False)
        
        with tempfile.NamedTemporaryFile('w+b', suffix='.xlsx', delete=False) as fp:
            #dft_tf_data.to_excel(writer, sheet_name=sheet_name, index=False)
            print('Inside Temp File creation')
            temp_file = path + f'/fp.xlsx'
            writer = pd.ExcelWriter(temp_file, engine = 'xlsxwriter')
            dft_tf_data.to_excel(writer, sheet_name=sheet_name, index=False)
            writer.save()
    print(temp_file) 

I am trying to achieve the below scenario.我正在尝试实现以下场景。

  1. Based on the FUNCTION_NAME, it should add a new sheet in the existing excel and then write the data from the query into the worksheet.基于FUNCTION_NAME,它应该在现有的excel中添加一个新工作表,然后将查询中的数据写入工作表。
  2. The final file should have all the worksheets.最终文件应包含所有工作表。

Is there a way to do it.有没有办法做到这一点。 Please suggest.请建议。

I'd only expect a file not found that to happen once (first run) if fp.xlsx doesn't exist.如果 fp.xlsx 不存在,我只希望找不到文件发生一次(第一次运行)。 fp.xlsx gets created on the line fp.xlsx 在线创建

writer= 

if it doesn't exist and since the line is referencing that file it must exist or the file not found error will occur.如果它不存在,并且由于该行引用该文件,它必须存在,否则将发生找不到文件的错误。 Once it exists then there should be no problems.一旦存在,就不会有任何问题。

I'm not sure of the reasoning of creating a temp xlsx file.我不确定创建临时 xlsx 文件的原因。 I dont see why it would be needed and you dont appear to use it.我不明白为什么需要它,而且您似乎也没有使用它。

The following works fine for me, where fp.xlsx initially saved as a blank workbook before running the code.以下对我来说很好,其中 fp.xlsx 在运行代码之前最初保存为空白工作簿。

sheet_name = 'Sheet1'
with tempfile.NamedTemporaryFile('w+b', suffix='.xlsx', delete=False) as fp:
    print('Inside Temp File creation')
    temp_file = path + f'/fp.xlsx'
    writer = pd.ExcelWriter(temp_file,
                            mode='a',
                            if_sheet_exists='overlay',
                            engine='openpyxl')
    dft_tf_data.to_excel(writer,
                 sheet_name=sheet_name,
                 startrow=writer.sheets[sheet_name].max_row+2,
                 index=False)
    writer.save()
print(temp_file)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM