/// <summary>
/// Convert DataTable to Excel File
/// </summary>
/// <param name="filePath">Excel FilePath</param>
/// <param name="table">DataTable</param>
/// <param name="fileName">Excel Filename</param>
/// <returns></returns>
public bool Write(string filePath, DataTable table, string fileName)
{
try
{
bool success = false;
var today = Convert.ToDateTime(DateTime.Now).ToString("yyyyMMddHHmmss");
//delete existing files
// Util_Directory.DeleteFiles(filePath);
var newDir = filePath + "" + today;
//if dir not exist create
Util_Directory.CreateDirectory(newDir);
FileInfo file = new FileInfo(Path.Combine(newDir, fileName));
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var package = new ExcelPackage(file))
{
var workSheet = package.Workbook.Worksheets.Add("Sheet1");
//add column headers
var columns = table.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToList();
int i = 1;
foreach (var column in columns)
{
workSheet.Cells[1, i].Value = column;
i++;
}
// add row values
int startRow = 2;
foreach (DataRow row in table.Rows)
{
int startColumn = 1;
foreach (var item in row.ItemArray)
{
workSheet.Cells[startRow, startColumn].Value = item;
startColumn++;
}
startRow++;
}
workSheet.Cells.AutoFitColumns();
package.Save();
success = true;
}
return success;
}
catch (Exception)
{
throw;
}
}