Reputation: 31
I wrote this code below
string filePath = @"C:\report_data.xlsx";
// Saves the file via a FileInfo
var file = new FileInfo(filePath);
// Creates the package and make sure you wrap it in a using statement
using (var package = new ExcelPackage(file))
{
// Adds a new worksheet to the empty workbook
OfficeOpenXml.ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Report System - " + DateTime.Now.ToShortDateString());
// Starts to get data from database
for (int row = 1; row < 10; row++)
{
// Writes data from sql database to excel's columns
for (int col = 1; col < 10; col++)
{
worksheet.Cells[row, col].Value = row * col;
}// Ends writing data from sql database to excel's columns
}// Ends getting data from database
// Saves new workbook and we are done!
package.Save();
}
When i opened the file , it had nothing and the page was blank. But when i saw the file size , it increased . Why was the page blank while the file size increased and how can i write data to it ?
Remark : When i tried deleting the existing file and run a program, the program generated the file and the file had values displayed in the columns . On the other hand , i tried creating file first and then run the program and the result was blank like i said above .
Upvotes: 1
Views: 1744
Reputation: 31
I found out the answer . I just changed the line at
OfficeOpenXml.ExcelWorksheet worksheet =
package.Workbook.Worksheets.Add("Report System - " +
DateTime.Now.ToShortDateString());
to
OfficeOpenXml.ExcelWorksheet worksheet =
package.Workbook.Worksheets["Sheet1"];
and it worked !!.
Because Sheet1
is the default name of worksheet and it existed in my file at line:
string filePath = @"C:\report_data.xlsx";
Actually, in this case, package.Workbook.Worksheets.Add
means to add the worksheet's name and I found that it didn't have to add the worksheet's name because it already exists.
Upvotes: 1