All, This seemed to me a no issue but looks like there is one
I am creating an ExcelPackage from a DataTable (data retrieved from sql into dataTable), and i am copying it to a public property of type ExcelPackage (before saving) as i need to access this property from outside the class and save it there. But it looks like the package is not getting assigned to this property of same type
public ExcelPackage excelPackage { get; set; }
using (ExcelPackage package = new ExcelPackage())
{
try
{
//Worksheet for data
ExcelWorksheet ws = package.Workbook.Worksheets.Add("Data");
int i = 1;
//header row
foreach (DataRow dr in ds.Tables[1].Rows)
{
ws.Cells[1, i].Value = dr["header"].ToString();
i++;
}
//Start writing data from second row.
ws.Cells.LoadFromDataTable(ds.Tables[0], true);
}
catch (Exception ex)
{
}
excelPackage = package;
}
When i try to access "excelPackage" property from outside this class, i get null value for excelPackage.File, excelPackage.package, excelPackage.stream. How can we do this?
Your ExcelPackage
object is an IDisposable
which means it gets disposed at the end of your using{}
block.
You need to persist it somewhere outside of the using block before it gets disposed.
Some options:
1.Save the file to disk first with something like this:
var fInfo = new FileInfo(@"C:\Temp\myExcelFile.xlsx"));
excelPackage.SaveAs(fInfo);
2.Keep it in memory as a byte array (which needs to be declared out side the using{}
block):
byte[] xlsxFileBytes;
using (ExcelPackage package = new ExcelPackage())
{
//
// ... snip ..
//
xlsxFileBytes = package.GetAsByteArray();
}
in either case you can recreate the ExcelPackage
from the FileInfo
object or the byte array.
An other alternative could be to simply refactor your code to do whatever needs to be done with excelPackage
INSIDE the using block.
Stewart_R ir right - this is because file stream is closed after leaving 'using' block.
If for some reason you want to extend lifecycle of excelPackage, then you should postpone disposal of package resources.
1) get rid of using statement around ExcelPackage; 1) Mark containing class as IDisposable; 2) Implement IDisposable interface and clean up any resources in Dispose method;
Just be careful as extending lifecycle of that excel package instance can result in file being locked.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.