本文介绍了EPPlus:我怎么有2个ExcelPackage.SaveAs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EPPlus导出到Excel函数。我需要有2个SaveAs,第1个SaveAs是一个保存对话框,允许用户打开/保存/另存为,第二个SaveAs允许将Excel文件作为备份副本直接保存到服务器的指定文件夹中。

I am using EPPlus for my export to Excel function. I need to have 2 SaveAs, 1st SaveAs which is a save dialogue to allow user Open/Save/SaveAs and my 2nd SaveAs to allow the Excel file to be saved directly into the specified folder in the server as a backup copy.

因此,我的问题是我的第二个SaveAs不起作用(调试期间没有错误弹出窗口,也没有为第二个SaveAs生成任何文件)。

请咨询。

ExcelPackage package = new ExcelPackage();
.....
code for loading data table
.....
var filename = @"REPORT_" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx";

以下代码有效(我的第一个SaveAs供用户选择打开/保存/另存为):

The below codes works (my 1st SaveAs for user to choose to Open/Save/SaveAs):

Response.Clear();
package.SaveAs(Response.OutputStream);
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
Response.Charset = "";
Response.ContentType = "application/vnd.xlsx";
Response.End();

以下代码不起作用(我的第二次SaveAs将文件直接保存到服务器中):

The below code does not work (my 2nd SaveAs to save file directly into server):

string path = @"C:\Users\testacc\Desktop\Test\" + filename +";";
Stream stream = File.Create(path);
package.SaveAs(stream);
stream.Close();
byte[] data = File.ReadAllBytes(path);


推荐答案

为什么不看一下并实现另一种方式,以相反的顺序。首先将生成的文件保存在服务器上,然后将保存的文件传输到客户端。

Why not look at it and achieve the other way, in the reverse order. First save the generated file on the server and then transmit the saved file to the client.


  1. 创建包

  1. Create the package

ExcelPackage package = new ExcelPackage();
.....
code for loading data table
.....
var filename = @"REPORT_" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx";


  • 保存到服务器

  • Save to the server

    string path = @"C:\Users\testacc\Desktop\Test\" + filename +";";
    Stream stream = File.Create(path);
    package.SaveAs(stream);
    stream.Close();
    


  • 将保存的文件传输到客户端

  • Transmit saved file to the client

    try {
        response.Clear();
        response.ContentType = "application/vnd.xlsx";
        response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
        response.TransmitFile(path);
        response.Flush();
    } catch (Exception ex) {
        // any error handling mechanism
    } finally {
        HttpContext.Current.ApplicationInstance.CompleteRequest();
    }
    


  • 这篇关于EPPlus:我怎么有2个ExcelPackage.SaveAs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    10-11 10:17