1
votes

I have a text file with some information and I convert it to ExcelPackage Object using EPPlus, now I want to know if there is a way to open this object with excel without saving it to a local file? if is not possible can I use a temp directory to save it into a file, and then open it?

1

1 Answers

2
votes

If you are talking about a windows app, you could just use something like System.IO.Path.GetTempPath(). You can get more info from here:

How to get temporary folder for current user

So, something like this:

[TestMethod]
public void TempFolderTest()
{
    var path = Path.Combine(Path.GetTempPath(), "temp.xlsx");
    var tempfile = new FileInfo(path);
    if (tempfile.Exists)
        tempfile.Delete();

    //Save the file
    using (var pck = new ExcelPackage(tempfile))
    {
        var ws = pck.Workbook.Worksheets.Add("Demo");
        ws.Cells[1, 2].Value = "Excel Test";
        pck.Save();
    }

    //open the file
    Process.Start(tempfile.FullName);
}

if you are talking web you shouldn't need to save it all, just send it via Response:

using (ExcelPackage pck = new ExcelPackage())
{
    var ws = pck.Workbook.Worksheets.Add("Demo");
    ws.Cells[1, 2].Value = "Excel Test";

    var fileBytes = pck.GetAsByteArray();
    Response.Clear();

    Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
    Response.AppendHeader("Content-Disposition",
        String.Format("attachment; filename=\"{0}\"; size={1}; creation-date={2}; modification-date={2}; read-date={2}"
            , "temp.xlsx"
            , fileBytes.Length
            , DateTime.Now.ToString("R"))
        );
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    Response.BinaryWrite(fileBytes);
    Response.End();
}