I'm having a DataSet filled with different DataTables SQL-Results. Some of the DataTables are connected with a Excel-Template-File. So in the end in want to have an excelfile with a mixture of new worksheets and copied worksheets from some template.
That's why my code looks like this:
public void CopyResultToExcelFileWithTemplate(DataSet sourceResult, string exportFilePath, string sourceName, string templateExcelFilePath, string sheetName = null)
{
var excelFile = new FileInfo(exportFilePath);
var templateFile = new FileInfo(templateExcelFilePath);
if (string.IsNullOrEmpty(sheetName))
{
sheetName = sourceName;
}
// Open and get worksheets from template
using (var template = new ExcelPackage(templateFile))
{
var excelWorksheets = template.Workbook.Worksheets;
var sheetCount = 1;
foreach (DataTable resultTable in sourceResult.Tables)
{
var proposedSheetName = sourceResult.Tables.Count == 1 ? sheetName : string.Format("{0}_{1}", sheetName, sheetCount);
var currentWorksheet = excelWorksheets.FirstOrDefault(w => string.Equals(w.Name, proposedSheetName, StringComparison.CurrentCultureIgnoreCase)) ?? excelWorksheets.Add(proposedSheetName);
FillWorksheetWithDataTableContent(currentWorksheet, resultTable);
using (var excelToExport = new ExcelPackage(excelFile))
{
excelToExport.Workbook.Worksheets.Add(currentWorksheet.Name, currentWorksheet);
excelToExport.Save();
}
sheetCount++;
}
}
}
public void CopyResultToExcelFile(DataSet resultSet, string exportFilePath, string sourceName, string sheetName = null)
{
if (string.IsNullOrEmpty(sheetName))
{
sheetName = sourceName;
}
var excelToExport = new FileInfo(exportFilePath);
using (var excelPackage = new ExcelPackage(excelToExport))
{
var sheetCount = 1;
foreach (DataTable resultTable in resultSet.Tables)
{
var proposedSheetName = resultSet.Tables.Count == 1 ? sheetName : string.Format("{0}_{1}", sourceName, sheetCount);
var worksheet = excelPackage.Workbook.Worksheets.Add(proposedSheetName);
FillWorksheetWithDataTableContent(worksheet, resultTable);
sheetCount++;
}
excelPackage.Save();
}
}
So I fill the temporary created excelfile with a combination of worksheet-copys from a template and with new worksheets. It works fine, it shows the content of all DataTables in the excelfile in their own worksheet, BUT when the excelfile contains copied worksheets there are two error message appearing and the copied worksheets arent formatted.
My compromise looks like this: