public static void Createxlsx(string filename)
{
MemoryStream stream = new MemoryStream();
//create a package
using (var package = new ExcelPackage(stream)) // disposing ExcelPackage also disposes the above MemoryStream
{
var worksheet = package.Workbook.Worksheets.Add("worksheet");
package.Save();
// see the various ways to create/open a file, Create is just one of them
// open the file stream
using(var file = System.IO.File.Open("C:\\ConsoleApplicationXLSX\\" + filename + ".xlsx", System.IO.FileMode.CreateNew))
{
stream.Position = 0; // reset the position of the memory stream
stream.CopyTo(file); // copy the memory stream to the file stream
}
}
}
的一些注意事項
- 在
using
報表包裝你流(內存,文件等)。這將確保流在超出範圍之後始終釋放/釋放(使用實現的IDisposable接口)。
- 請參閱FileMode,如果您嘗試覆蓋現有文件,則我選擇的上述
CreateNew
以上的選項將引發異常。如果你不關心那個用Create
。
- 最後,您必須在複製流之前重置流的位置,否則它將拾取當前位置離開的位置,通常位於流的末尾。
編輯
你也可以這樣做沒有MemoryStream
。
public static void Createxlsx(string filename)
{
using(var file = System.IO.File.Open("C:\\ConsoleApplicationXLSX\\" + filename + ".xlsx", System.IO.FileMode.CreateNew))
using (var package = new ExcelPackage(file)) // disposing ExcelPackage also disposes the above MemoryStream
{
var worksheet = package.Workbook.Worksheets.Add("worksheet");
package.Save();
}
}