Save as using EPPlus?

走远了吗. 提交于 2019-11-28 09:04:25

The package will be closed & disposed after you call any of functions GetAsByteArray, Save, SaveAs. That is the reason why you got message

Package object was closed and disposed, so cannot carry out operations on this object or any stream opened on a part of this package.

The solution is that after the saving you call Load function to continue processing on excel file. Or if you just want to get both ByteArray & FileOutput, I'm sure with you they both are same.

You can read data after have saved file to the disk:

string path = @"C:\test1.xlsx";
Stream stream = File.Create(path);
package.SaveAs(stream);
stream.Close();

byte[] data = File.ReadAllBytes(path);

Or you can save data to disk after get the ByteArray:

byte[] data = package.GetAsByteArray();

string path = @"C:\test1.xlsx";
File.WriteAllBytes(path, data);

I came looking for the answer to this but the existing answers were not clear to me. Here is what I did using EPPlus and System.Windows.Forms:

ExcelPackage xlPackage = new ExcelPackage(xlsTmpFileName)

// Populate the Excel spreadsheet here.

SaveFileDialog sfd = new SaveFileDialog();
using (FileStream fs = new FileStream(sfd.FileName, FileMode.Create))
{
    xlPackage.SaveAs(fs);
}
nawfal

I dont know from which version onwards but EPPlus's SaveAs method accepts a FileInfo. So you could do something like this:

using (var app = new ExcelPackage(new FileInfo(inputPath)))
{
    //process
    app.SaveAs(new FileInfo(outputPath));
}

Unlike the Save method SaveAs method overwrites file as well in case file name already exists.

SaveAs would be accepting your aFile Stream.

You can find out such things yourself by looking at the function signature: SaveAs(System.IO.Stream). It takes a Stream. Passing a string cannot possibly compile so you have to somehow make up a useful Stream (which you did).

Get rid of the surplus package.GetAsByteArray call and you should solve it.

I just ran:

using (FileStream aFile = new FileStream(@"C:\Temp\asdf.xlsx", FileMode.Create))
{
    aFile.Seek(0, SeekOrigin.Begin);
    package.SaveAs(aFile);
    aFile.Close();
}

// See here - I can still work with the spread sheet.
var worksheet = package.Workbook.Worksheets.Single(); 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!