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
226 views
in Technique[技术] by (71.8m points)

c# - Save as using EPPlus?

Does any one know how to use the package.Saveas function?

package.SaveAs(tempFolderPathAlt + saveas + ".xlsx");

At the moment this is underlined in red with the following error:

The best overloaded method match for 'OfficeOpenXml.ExcelPackage.SaveAs(System.IO.Stream)' has some invalid arguments

At the moment i'm saving the file in the following way.

FileStream aFile = new FileStream(tempFolderPathAlt + saveas + ".xls",    FileMode.Create);
byte[] byData = package.GetAsByteArray();
aFile.Seek(0, SeekOrigin.Begin);
aFile.Write(byData, 0, byData.Length);
aFile.Close();

But this way the package remains open and i cant work with files it has used.

The save as will close the package properly, but its not accepting my file path.


Edit

I tried this:

using (FileStream aFile = new FileStream(tempFolderPathAlt + saveas + ".xlsx", FileMode.Create))
{
    byte[] byData = package.GetAsByteArray();
    aFile.Seek(0, SeekOrigin.Begin);
    package.SaveAs(aFile);
    //aFile.Write(byData, 0, byData.Length);
    aFile.Close();
}

But Get the following error?

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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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:est1.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:est1.xlsx";
File.WriteAllBytes(path, data);

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

...