Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

c# - Open ExcelPackage Object with Excel application without saving it on local file path

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...