I am trying to generate multiple worksheets for every student in my list but not sure how to achieve this,i can generate Excel document with one worksheet successfully but shows all students in one sheet,how can i generate a new sheet for every student?i tried achieving this with the code below thanks.
public FileContentResult GenerateStudentReport([FromForm] Student Students)
{
int count = 0;
Workbook workbook = new Workbook();
Worksheet worksheet;
foreach (var item in Students)
{
worksheet = workbook.Worksheets[count];
var dataSet = new DataSet();
// Add the new DataTable to the DataSet.
dataSet.Tables.Add(table);
row["studentid"] = Convert.ToString(item.id);
row["studentName"] = Convert.ToString(item.Name);
row["studentSurname"] = Convert.ToString(item.Surname);...
table.Rows.Add(row);
worksheet[count].Import(table, true, 0, 0);
worksheet[count]["A1:V1"].Font.Bold = true;
worksheet[count]["A1:V1"].ColumnWidth = 300;
worksheet[count]["A1:V1"].Style.NumberFormat = "0.00";
worksheet[count].Import(table, true, 0, 0);
count++;
}
byte[] docBytes = workbook.SaveDocument(DocumentFormat.Xlsx);
return File(docBytes, "application/vnd.ms-excel", $"ExportForecastReport_{DateTime.Now.ToString("HH-mm-ss yyyyy-dd-MM")}.xlsx"); // returns a FileStreamResult
}
error thrown while trying to generate second worksheet:{"Worksheet index should be positive and less than the number of worksheets. (Parameter 'index')"}
You should be able to do so with the following:
var newWorksheet = (Excel.Worksheet)this.Application.Worksheets.Add();
The idea is that you first add a new, empty Worksheet to the workbook and then work on it (similarly to what you would do manually in Excel)
You can use EPPlus Nuget package in your project, Then use below code.
public IActionResult EveryExcel([FromForm] Student users)
{
var stream = new MemoryStream();
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var xlPackage = new ExcelPackage(stream))
{
int i = 1;
foreach(var user in users)
{
var worksheet = xlPackage.Workbook.Worksheets.Add($"StudentAll{i}");
var namedStyle = xlPackage.Workbook.Styles.CreateNamedStyle($"HyperLink{i}");
namedStyle.Style.Font.UnderLine = true;
namedStyle.Style.Font.Color.SetColor(Color.Blue);
const int startRow = 5;
var row = startRow;
worksheet.Cells["A1"].Value = "Sample";
using (var r = worksheet.Cells["A1:C1"])
{
r.Merge = true;
r.Style.Font.Color.SetColor(Color.White);
r.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.CenterContinuous;
r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
r.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(23, 55, 93));
}
worksheet.Cells["A4"].Value = "ID";
worksheet.Cells["B4"].Value = "Name";
worksheet.Cells["C4"].Value = "Surname";
worksheet.Cells["A4:C4"].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells["A4:C4"].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(184, 204, 228));
worksheet.Cells["A4:C4"].Style.Font.Bold = true;
worksheet.Cells[row, 1].Value = user.Id;
worksheet.Cells[row, 2].Value = user.Name;
worksheet.Cells[row, 3].Value = user.Surname;
i++;
}
xlPackage.Save();
}
stream.Position = 0;
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "students.xlsx");
}
Then it will generate a new sheet for every student
Related
I am getting error 'Excel found unreadable content in APPL_1.xlsx.'
What is wrong in my code?.
Record contain around 2 lacks data. I am trying to fetch it from datatable to excel.
I am using OpenXMLSpreedsheetDocument to fetch data from datatable to excel
FileInfo FileLoc = new FileInfo(FilePath);
if (FileLoc.Exists)
{
FileLoc.Delete();
FileLoc = new FileInfo(FilePath);
}
SpreadsheetDocument spreadSheet = SpreadsheetDocument.
Create(FilePath, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadSheet.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
worksheetPart.Worksheet = new Worksheet(sheetData);
var bold1 = new Bold();
CellFormat cf = new CellFormat();
// Add Sheets to the Workbook.
Sheets sheets;
sheets = spreadSheet.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
var sheet = new Sheet()
{
Id = spreadSheet.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = 0,
Name = "Sheet" + 0
};
sheets.Append(sheet);
//Add Header Row.
var headerRow = new Row();
foreach (DataColumn column in dt.Columns)
{
var cell = new Cell
{
DataType = CellValues.String,
CellValue = new CellValue(column.ColumnName)
};
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow row in dt.Rows)
{
var newRow = new Row();
foreach (DataColumn col in dt.Columns)
{
Cell c = new Cell();
c.DataType = new EnumValue<CellValues>(CellValues.String);
c.CellValue = new CellValue(row[col].ToString());
newRow.Append(c);
}
sheetData.AppendChild(newRow);
}
workbookpart.Workbook.Save();
ProcessStartInfo startInfo = new ProcessStartInfo(FilePath);
Process.Start(startInfo);
Any suggestions is much appreciated..!!
Here is my implementation of OpenXML. For simplicity, I have excluded the cell styling code.
This creates an excel file with two rows and 3 columns. You can modify this to suit your needs.
Main method:
static void Main(string[] args)
{
var dtToXl = new DtToExcel();
var dt = new DataTable();
dt.Columns.Add("Col1");
dt.Columns.Add("Col2");
dt.Columns.Add("Col3");
dt.Rows.Add("R1C1", "R1C2", "R1C3");
dt.Rows.Add("R2C1", "R2C2", "R2C3");
dtToXl.GetExcel(dt);
if(Debugger.IsAttached)
{
Console.ReadLine();
}
}
GetExcel method:
public void GetExcel(DataTable dt)
{
using (var document = SpreadsheetDocument.Create("C:\\Desktop\\Excel1.xlsx", SpreadsheetDocumentType.Workbook))
{
var workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
var sheets = workbookPart.Workbook.AppendChild(new Sheets());
AddWorksheet(dt, 1, ref sheets, ref workbookPart);
}
}
AddWorksheet method:
private void AddWorksheet(DataTable dt, int sheetCount, ref Sheets sheets, ref WorkbookPart workbookPart)
{
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
var sheetName = $"Sheet{sheetCount}";
worksheetPart.Worksheet = new Worksheet();
//Create header rows
#region Excel Headers
Row row = new Row
{
RowIndex = 1
};
row.AppendChild(AddCellWithValue("Column 1", CellValues.InlineString));
row.AppendChild(AddCellWithValue("Column 2", CellValues.InlineString));
row.AppendChild(AddCellWithValue("Column 3", CellValues.InlineString));
sheetData.AppendChild(row);
#endregion
//Create data rows
#region Excel data rows
var rowIndex = (UInt32)2;
foreach (DataRow dtRow in dt.Rows)
{
row = new Row
{
RowIndex = rowIndex++
};
row.AppendChild(AddCellWithValue(dtRow[0].ToString(), CellValues.InlineString));
row.AppendChild(AddCellWithValue(dtRow[1].ToString(), CellValues.InlineString));
row.AppendChild(AddCellWithValue(dtRow[2].ToString(), CellValues.InlineString));
sheetData.AppendChild(row);
}
#endregion
var columns = new Columns();
columns.Append(new Column() { Min = 1, Max = 1, Width = 20, CustomWidth = true });
columns.Append(new Column() { Min = 2, Max = 2, Width = 20, CustomWidth = true });
columns.Append(new Column() { Min = 3, Max = 3, Width = 20, CustomWidth = true });
worksheetPart.Worksheet.Append(columns);
worksheetPart.Worksheet.Append(sheetData); //This line should be anywhere below .Append(columns)
var sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = (UInt32)sheetCount, Name = sheetName };
sheets.Append(sheet);
}
AddCellWithValue method
private Cell AddCellWithValue(string value, CellValues type)
{
var cell = new Cell
{
DataType = type
};
if (type == CellValues.InlineString)
{
var inlineString = new InlineString();
var t = new Text
{
Text = value
};
inlineString.AppendChild(t);
cell.AppendChild(inlineString);
}
else
{
cell.CellValue = new CellValue(value);
}
return cell;
}
I have used SpreadsheetLight.
Here is my code.
using SpreadsheetLight;
SLDocument sl = new SLDocument();
int iStartRowIndex = 1;
int iStartColumnIndex = 1;
sl.ImportDataTable(iStartRowIndex, iStartColumnIndex, dt, true);
// + 1 because the header row is included
// - 1 because it's a counting thing, because the start row is counted.
int iEndRowIndex = iStartRowIndex + dt.Rows.Count + 1 - 1;
// - 1 because it's a counting thing, because the start column is counted.
int iEndColumnIndex = iStartColumnIndex + dt.Columns.Count - 1;
SLTable table = sl.CreateTable(iStartRowIndex, iStartColumnIndex, iEndRowIndex, iEndColumnIndex);
table.SetTableStyle(SLTableStyleTypeValues.Medium17);
table.HasTotalRow = true;
table.SetTotalRowFunction(5, SLTotalsRowFunctionValues.Sum);
sl.InsertTable(table);
sl.SaveAs(FilePath);
sl.Dispose();
ProcessStartInfo startInfo = new ProcessStartInfo(FilePath);
Process.Start(startInfo);
I am current working on export the object into .xlsx file. This is so close to what i need, Export xlsx in ASP.NET Core
, but the problem is - this is export to the local project folder wwwroot, and i want export to client machine.
i had tried this.
private readonly IHostingEnvironment _hostingEnvironment;
public ImportExportController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpGet]
[Route("Export")]
public FileStreamResult Export()
{
string sWebRootFolder = _hostingEnvironment.WebRootPath;
string sFileName = #"demo.xlsx";
string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
if (file.Exists)
{
file.Delete();
file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
}
using (ExcelPackage package = new ExcelPackage(file))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
//First add the headers
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
worksheet.Cells[1, 3].Value = "Gender";
worksheet.Cells[1, 4].Value = "Salary (in $)";
//Add values
worksheet.Cells["A2"].Value = 1000;
worksheet.Cells["B2"].Value = "Jon";
worksheet.Cells["C2"].Value = "M";
worksheet.Cells["D2"].Value = 5000;
worksheet.Cells["A3"].Value = 1001;
worksheet.Cells["B3"].Value = "Graham";
worksheet.Cells["C3"].Value = "M";
worksheet.Cells["D3"].Value = 10000;
worksheet.Cells["A4"].Value = 1002;
worksheet.Cells["B4"].Value = "Jenny";
worksheet.Cells["C4"].Value = "F";
worksheet.Cells["D4"].Value = 5000;
package.Save(); //Save the workbook.
}
FileStream RptStream = new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Open, FileAccess.Read);
return new FileStreamResult(RptStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
but seems like i need to export the worksheet to wwwroot folder and later on return filestreamresult with the worksheet url. and i dont know how to get the url of the worksheet to pass in filestreamresult function.
Anyone can help me?
I want to export this .xlsx on client machine instead of wwwroot.
Try Writing the file to a memory stream and having your method return a FileContentResult object (via Controller.File Method):
var stream = new MemoryStream(package.GetAsByteArray());
return File(stream.ToArray(), "application/vnd.ms-excel", sFileName);
in asp.net Core there is a library you can use named "EPPlus"
download its nugget by add in Package manager console "Install-Package EPPlus -Version 4.5.2.1" then use the below code in the controller
there is a comment before every line for description.
public async Task<IActionResult> Export()
{
await Task.Yield();
//Lets we have object userInfo so we will fill it
var list = new List<UserInfo>()
{
new UserInfo { UserName = "catcher", Age = 18 },
new UserInfo { UserName = "james", Age = 20 },
};
// Then use system.IO.MemeoryStream
var stream = new MemoryStream();
//Then generate the Sheet by below code "using OfficeOpenXml;" from EPPlus nugget
using (var package = new ExcelPackage(stream))
{
//name the sheet "Sheet1"
var workSheet = package.Workbook.Worksheets.Add("Sheet1");
// simple way
workSheet.Cells.LoadFromCollection(list, true);
//// mutual
//workSheet.Row(1).Height = 20;
//workSheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
//workSheet.Row(1).Style.Font.Bold = true;
//workSheet.Cells[1, 1].Value = "No";
//workSheet.Cells[1, 2].Value = "Name";
//workSheet.Cells[1, 3].Value = "Age";
//int recordIndex = 2;
//foreach (var item in list)
//{
// workSheet.Cells[recordIndex, 1].Value = (recordIndex - 1).ToString();
// workSheet.Cells[recordIndex, 2].Value = item.UserName;
// workSheet.Cells[recordIndex, 3].Value = item.Age;
// recordIndex++;
//}
package.Save();
}
stream.Position = 0;
//Name the file which will download
string excelName = $"UserInfoList-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx";
//Then download
return File(stream, "application/octet-stream", excelName);
}
reference link
https://www.c-sharpcorner.com/article/using-epplus-to-import-and-export-data-in-asp-net-core/
I am reading XML data then I pasted to data-set and the I created spreadsheet and copied the data to to sheets in spreadsheet.So now I want to only allow some sheets and cells to read-only. To prevent to no changes to headers and data in some sheets, So I am posting code used to convert the XML to excel using open XML. So I need to prevent write for some sheets and also cells some sheets.
public void ExportDSToExcel(DataSet ds, string dest)
{
using (var workbook = SpreadsheetDocument.Create(dest, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
var workbookPart = workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();
uint sheetId = 1;
foreach (DataTable table in ds.Tables)
{
var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);
DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);
if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
{
sheetId =
sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
sheets.Append(sheet);
DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
List<String> columns = new List<string>();
foreach (DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow dsrow in table.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
foreach (String col in columns)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if(txtname.Text != null)
{
if (FileUpload1.HasFile == true)
{
string myXMLfile = "/uploads/" + FileUpload1.FileName;
FileUpload1.SaveAs(Server.MapPath(myXMLfile));
string dest = "D:/uploads/" + txtname.Text+".xlsx";
DataSet ds = new DataSet();
try
{
ds.ReadXml(myXMLfile);
}
catch (Exception ex)
{
lblstatus.Text=(ex.ToString());
}
ExportDSToExcel(ds, dest);
}
else
{
lblstatus.Text = "Please Upload the file ";
}
}
else {
lblstatus.Text = "Please enter the name ";
}
}
}
thanks in advance so please help me to find solution in this code.
We can customise protection by password in different means.For making excel sheet specified area or column or row as read only or a full sheet into read only by giving protection to sheet by password.If we want to protect whole sheet use this code
PageMargins pageM = sheetPart.Worksheet.GetFirstChild<PageMargins>();
SheetProtection sheetProtection = new SheetProtection();
sheetProtection.Password = "admin";
sheetProtection.Sheet = true;
sheetProtection.Objects = true;
sheetProtection.Scenarios = true;
ProtectedRanges pRanges = new ProtectedRanges();
ProtectedRange pRange = new ProtectedRange();
ListValue<StringValue> lValue = new ListValue<StringValue>();
lValue.InnerText = ""; //set cell which you want to make it editable
pRange.SequenceOfReferences = lValue;
pRange.Name = "not allow editing";
pRanges.Append(pRange);
sheetPart.Worksheet.InsertBefore(sheetProtection, pageM);
sheetPart.Worksheet.InsertBefore(pRanges, pageM);
If we want specified page as read only then first give a condition filter by name then give this code .In this code lValue.InnerText = ""; is null so we are not mention cells have permission to overcome this protection. If we mention the cells we can edit up to that limit.
I am using the EPPlus library to generate an excel file which I successfully save in a folder on the server.
How can download this file to my local machine?
This is my code
public void CreateExcelFirstTemplate()
{
var fileName = "C:\ExcelDataTest\ExcellData.xlsx";
var file = new FileInfo(fileName);
using (var package = new OfficeOpenXml.ExcelPackage(file))
{
var worksheet = package.Workbook.Worksheets.FirstOrDefault(x => x.Name == "Attempts");
worksheet = package.Workbook.Worksheets.Add("Assessment Attempts");
worksheet.Row(1).Height = 20;
worksheet.TabColor = Color.Gold;
worksheet.DefaultRowHeight = 12;
worksheet.Row(1).Height = 20;
worksheet.Cells[1, 1].Value = "Employee Number";
worksheet.Cells[1, 2].Value = "Course Code";
var cells = worksheet.Cells["A1:J1"];
var rowCounter = 2;
foreach (var v in userAssessmentsData)
{
worksheet.Cells[rowCounter, 1].Value = v.CompanyNumber;
worksheet.Cells[rowCounter, 2].Value = v.CourseCode;
rowCounter++;
}
worksheet.Column(1).AutoFit();
worksheet.Column(2).AutoFit();
package.Workbook.Properties.Title = "Attempts";
package.Save();
}
}
If you are generating this file on each request you don't need to save it on the server:
public void CreateExcelFirstTemplate()
{
var fileName = "ExcellData.xlsx";
using (var package = new OfficeOpenXml.ExcelPackage(fileName))
{
var worksheet = package.Workbook.Worksheets.FirstOrDefault(x => x.Name == "Attempts");
worksheet = package.Workbook.Worksheets.Add("Assessment Attempts");
worksheet.Row(1).Height = 20;
worksheet.TabColor = Color.Gold;
worksheet.DefaultRowHeight = 12;
worksheet.Row(1).Height = 20;
worksheet.Cells[1, 1].Value = "Employee Number";
worksheet.Cells[1, 2].Value = "Course Code";
var cells = worksheet.Cells["A1:J1"];
var rowCounter = 2;
foreach (var v in userAssessmentsData)
{
worksheet.Cells[rowCounter, 1].Value = v.CompanyNumber;
worksheet.Cells[rowCounter, 2].Value = v.CourseCode;
rowCounter++;
}
worksheet.Column(1).AutoFit();
worksheet.Column(2).AutoFit();
package.Workbook.Properties.Title = "Attempts";
this.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
this.Response.AddHeader(
"content-disposition",
string.Format("attachment; filename={0}", "ExcellData.xlsx"));
this.Response.BinaryWrite(package.GetAsByteArray());
}
}
Instead of using package.Save() you can use package.GetAsByteArray() which will return a byte array which you can then stream using FileResult or FileContentResult from the MVC action to trigger a file download. This method will allow you to download the file without saving it to the server first.
Here is sample action to download file. Feel free to modify it as per your requirement.
public FileActionResult DownloadMyFile()
{
var filePath = "C:\ExcelDataTest\ExcellData.xlsx";
var fileName = "ExcellData.xlsx";
var mimeType = "application/vnd.ms-excel";
return File(new FileStream(filePath, FileMode.Open),mimeType, fileName);
}
You can do like this:
excel.Workbook.Properties.Title = "Attempts";
this.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
this.Response.AddHeader("content-disposition",string.Format("attachment; filename={0}", "ExcellData.xlsx"));
this.Response.BinaryWrite(excel.GetAsByteArray());
For detailed blog: http://sforsuresh.in/generating-and-formatting-excelsheet-in-c-using-epplus/
I have recently discovered EPPlus (http://epplus.codeplex.com/).
I have an excel .xlsx file in my project with all the styled column headers.
I read on their site that you can use templates.
Does anyone know how or can provide code sample of how to use my template.xlsx file with EPPlus? I would like to be able to simply load my data into the rows without messing with the headings.
The solution I ended up going with:
using System.IO;
using System.Reflection;
using OfficeOpenXml;
//Create a stream of .xlsx file contained within my project using reflection
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EPPlusTest.templates.VendorTemplate.xlsx");
//EPPlusTest = Namespace/Project
//templates = folder
//VendorTemplate.xlsx = file
//ExcelPackage has a constructor that only requires a stream.
ExcelPackage pck = new OfficeOpenXml.ExcelPackage(stream);
After that you can use all the methods of ExcelPackage that you want on an .xlsx file loaded from a template.
To create a new package, you can provide a stream template:
// templateName = the name of .xlsx file
// result = stream to write the resulting xlsx to
using (var source = System.IO.File.OpenRead(templateName))
using (var excel = new OfficeOpenXml.ExcelPackage(result, source)) {
// Fill cells here
// Leave headers etc as is
excel.Save();
}
//This is my Implementation for EPPlus. // may be it helps.
class EPPlus
{
FileInfo newFile;
FileInfo templateFile;
DataSet _ds;
ExcelPackage xlPackage;
public string _ErrorMessage;
public EPPlus(string filePath, string templateFilePath)
{
newFile = new FileInfo(#filePath);
templateFile = new FileInfo(#templateFilePath);
_ds = GetDataTables(); /* DataTables */
_ErrorMessage = string.Empty;
CreateFileWithTemplate();
}
private bool CreateFileWithTemplate()
{
try
{
_ErrorMessage = string.Empty;
using (xlPackage = new ExcelPackage(newFile, templateFile))
{
int i = 1;
foreach (DataTable dt in _ds.Tables)
{
AddSheetWithTemplate(xlPackage, dt, i);
i++;
}
///* Set title, Author.. */
//xlPackage.Workbook.Properties.Title = "Title: Office Open XML Sample";
//xlPackage.Workbook.Properties.Author = "Author: Muhammad Mubashir.";
////xlPackage.Workbook.Properties.SetCustomPropertyValue("EmployeeID", "1147");
//xlPackage.Workbook.Properties.Comments = "Sample Record Details";
//xlPackage.Workbook.Properties.Company = "TRG Tech.";
///* Save */
xlPackage.Save();
}
return true;
}
catch (Exception ex)
{
_ErrorMessage = ex.Message.ToString();
return false;
}
}
/// <summary>
/// This AddSheet method generates a .xlsx Sheet with your provided Template file, //DataTable and SheetIndex.
/// </summary>
public static void AddSheetWithTemplate(ExcelPackage xlApp, DataTable dt, int SheetIndex)
{
string _SheetName = string.Format("Sheet{0}", SheetIndex.ToString());
ExcelWorksheet worksheet;
/* WorkSheet */
if (SheetIndex == 0)
{
worksheet = xlApp.Workbook.Worksheets[SheetIndex + 1]; // add a new worksheet to the empty workbook
}
else
{
worksheet = xlApp.Workbook.Worksheets[SheetIndex]; // add a new worksheet to the empty workbook
}
if (worksheet == null)
{
worksheet = xlApp.Workbook.Worksheets.Add(_SheetName); // add a new worksheet to the empty workbook
}
else
{
}
/* Load the datatable into the sheet, starting from cell A1. Print the column names on row 1 */
worksheet.Cells["A1"].LoadFromDataTable(dt, true);
}
private static void AddSheet(ExcelPackage xlApp, DataTable dt, int Index, string sheetName)
{
string _SheetName = string.Empty;
if (string.IsNullOrEmpty(sheetName) == true)
{
_SheetName = string.Format("Sheet{0}", Index.ToString());
}
else
{
_SheetName = sheetName;
}
/* WorkSheet */
ExcelWorksheet worksheet = xlApp.Workbook.Worksheets[_SheetName]; // add a new worksheet to the empty workbook
if (worksheet == null)
{
worksheet = xlApp.Workbook.Worksheets.Add(_SheetName); // add a new worksheet to the empty workbook
}
else
{
}
/* Load the datatable into the sheet, starting from cell A1. Print the column names on row 1 */
worksheet.Cells["A1"].LoadFromDataTable(dt, true);
int rowCount = dt.Rows.Count;
int colCount = dt.Columns.Count;
#region Set Column Type to Date using LINQ.
/*
IEnumerable<int> dateColumns = from DataColumn d in dt.Columns
where d.DataType == typeof(DateTime) || d.ColumnName.Contains("Date")
select d.Ordinal + 1;
foreach (int dc in dateColumns)
{
xlSheet.Cells[2, dc, rowCount + 1, dc].Style.Numberformat.Format = "dd/MM/yyyy";
}
*/
#endregion
#region Set Column Type to Date using LOOP.
/* Set Column Type to Date. */
for (int i = 0; i < dt.Columns.Count; i++)
{
if ((dt.Columns[i].DataType).FullName == "System.DateTime" && (dt.Columns[i].DataType).Name == "DateTime")
{
//worksheet.Cells[2,4] .Style.Numberformat.Format = "yyyy-mm-dd h:mm"; //OR "yyyy-mm-dd h:mm" if you want to include the time!
worksheet.Column(i + 1).Style.Numberformat.Format = "dd/MM/yyyy h:mm"; //OR "yyyy-mm-dd h:mm" if you want to include the time!
worksheet.Column(i + 1).Width = 25;
}
}
#endregion
//(from DataColumn d in dt.Columns select d.Ordinal + 1).ToList().ForEach(dc =>
//{
// //background color
// worksheet.Cells[1, 1, 1, dc].Style.Fill.PatternType = ExcelFillStyle.Solid;
// worksheet.Cells[1, 1, 1, dc].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightYellow);
// //border
// worksheet.Cells[1, dc, rowCount + 1, dc].Style.Border.Top.Style = ExcelBorderStyle.Thin;
// worksheet.Cells[1, dc, rowCount + 1, dc].Style.Border.Right.Style = ExcelBorderStyle.Thin;
// worksheet.Cells[1, dc, rowCount + 1, dc].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
// worksheet.Cells[1, dc, rowCount + 1, dc].Style.Border.Left.Style = ExcelBorderStyle.Thin;
// worksheet.Cells[1, dc, rowCount + 1, dc].Style.Border.Top.Color.SetColor(System.Drawing.Color.LightGray);
// worksheet.Cells[1, dc, rowCount + 1, dc].Style.Border.Right.Color.SetColor(System.Drawing.Color.LightGray);
// worksheet.Cells[1, dc, rowCount + 1, dc].Style.Border.Bottom.Color.SetColor(System.Drawing.Color.LightGray);
// worksheet.Cells[1, dc, rowCount + 1, dc].Style.Border.Left.Color.SetColor(System.Drawing.Color.LightGray);
//});
/* Format the header: Prepare the range for the column headers */
string cellRange = "A1:" + Convert.ToChar('A' + colCount - 1) + 1;
using (ExcelRange rng = worksheet.Cells[cellRange])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189)); //Set color to dark blue
rng.Style.Font.Color.SetColor(Color.White);
}
/* Header Footer */
worksheet.HeaderFooter.OddHeader.CenteredText = "Header: Tinned Goods Sales";
worksheet.HeaderFooter.OddFooter.RightAlignedText = string.Format("Footer: Page {0} of {1}", ExcelHeaderFooter.PageNumber, ExcelHeaderFooter.NumberOfPages); // add the page number to the footer plus the total number of pages
}
}// class End.
I use Vb.net, here is what I did:
VB
Imports OfficeOpenXml
Dim existingFile As New FileInfo("C:\OldFileLocation\File.xlsx")
Dim fNewFile As New FileInfo("C:\NewFileLocation\File.xlsx")
Using MyExcel As New ExcelPackage(existingFile)
Dim MyWorksheet As ExcelWorksheet = MyExcel.Workbook.Worksheets("ExistingSheetName")
MyWorksheet.Cells("A1").Value = "Hello"
'Add additional info here
MyExcel.SaveAs(fNewFile)
End Using
Posible C# (I did not test)
FileInfo existingFile = new FileInfo("C:\\OldFileLocation\\File.xlsx");
FileInfo fNewFile = new FileInfo("C:\\NewFileLocation\\File.xlsx");
using (ExcelPackage MyExcel = new ExcelPackage(existingFile)) {
ExcelWorksheet MyWorksheet = MyExcel.Workbook.Worksheets["ExistingSheetName"];
MyWorksheet.Cells["A1"].Value = "Hello";
//Add additional info here
MyExcel.SaveAs(fNewFile);
}
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode("Logs.xlsx", System.Text.Encoding.UTF8));
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Logs");
ws.Cells["A1"].LoadFromDataTable(dt, true);
var ms = new System.IO.MemoryStream();
pck.SaveAs(ms);
ms.WriteTo(Response.OutputStream);
}