Need to add logo in the top of the excel file while downloading.
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ClearContent();
Response.ClearHeaders();
string FileName = "MachinePlanning" + DateTime.Now + ".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
GridView1.GridLines = GridLines.Both;
GridView1.HeaderStyle.Font.Bold = true;
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
You need to do it by Open XML or NPOI.Dll.
Below code will export excel with the company logo. but you need to add NPOI.DLL.
public static MemoryStream ExportToExcelWithCompanyLogo(DataTable dt, string sheetName, string CompanyLogo,Dictionary<string, string> filters)
{
//Create new Excel Workbook
var workbook = new HSSFWorkbook();
//Create new Excel Sheet
var sheet = workbook.CreateSheet(sheetName);
// Add Image Section
var patriarch = sheet.CreateDrawingPatriarch();
HSSFClientAnchor anchor;
anchor = new HSSFClientAnchor(0, 0, 0, 0, (short)1, 1, (short)5, 6);
anchor.AnchorType = 2;
string imagesPath = CompanyLogo;
//grab the image file
//imagesPath = System.IO.Path.Combine(imageLocation, "image.jpg");
//create an image from the path
System.Drawing.Image image = System.Drawing.Image.FromFile(imagesPath);
MemoryStream ims = new MemoryStream();
//pull the memory stream from the image (I need this for the byte array later)
image.Save(ims, System.Drawing.Imaging.ImageFormat.Jpeg);
int index = workbook.AddPicture(ims.ToArray(), PictureType.JPEG);
var picture = patriarch.CreatePicture(anchor, index);
picture.Resize(0.8);
//picture.LineStyle = HSSFPicture.LINESTYLE_DASHDOTGEL;
sheet.ForceFormulaRecalculation = true;
// End of Add image
// font Style for Excel title
HSSFFont hFont = (HSSFFont)workbook.CreateFont();
hFont.FontHeightInPoints = 16;
hFont.FontName = "Calibri";
hFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
HSSFCellStyle hStyle = (HSSFCellStyle)workbook.CreateCellStyle();
hStyle.Alignment = HorizontalAlignment.Center;
hStyle.VerticalAlignment = VerticalAlignment.Top;
hStyle.SetFont(hFont);
// end of excel title style
// font for Table header Stylr
HSSFFont thhFont = (HSSFFont)workbook.CreateFont();
thhFont.FontHeightInPoints = 12;
thhFont.FontName = "Calibri";
thhFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
HSSFCellStyle thhStyle = (HSSFCellStyle)workbook.CreateCellStyle();
thhStyle.Alignment = HorizontalAlignment.Left;
thhStyle.VerticalAlignment = VerticalAlignment.Top;
thhStyle.SetFont(thhFont);
// end of table header font
var cra = new NPOI.SS.Util.CellRangeAddress(6, 7, 4, 9);
sheet.AddMergedRegion(cra);
// Add filters to sheet
int filterRows = 9;
foreach (var key in filters)
{
var FilterRow = sheet.CreateRow(filterRows);
FilterRow.CreateCell(4).SetCellValue(key.Key + " : ");
FilterRow.CreateCell(5).SetCellValue(key.Value);
filterRows++;
}
var HeaderRowNumber = 9 + filters.Keys.Count + 1;
//Add rows
var headerRow = sheet.CreateRow(HeaderRowNumber);
//int totalcolumns = dt.Columns.Count;
int columncounter = 0;
if (dt.Rows.Count > 0)
{
foreach (DataColumn c in dt.Columns)
{
var cell = headerRow.CreateCell(columncounter + 1);
cell.SetCellValue(c.ColumnName);
cell.CellStyle = thhStyle;
columncounter++;
}
//(Optional) freeze the header row so it is not scrolled
//sheet.CreateFreezePane(0, 1, 0, 1);
int rowNumber = HeaderRowNumber + 1;
int dtrowNumber = 1;
//Populate the sheet with values from the grid data
foreach (var rows in dt.Rows)
{
//Create a new Row
var row = sheet.CreateRow(rowNumber);
//Set cell Value
for (int cellnumber = 0; cellnumber < columncounter; cellnumber++)
row.CreateCell(cellnumber + 1).SetCellValue(dt.Rows[dtrowNumber - 1][cellnumber].ToString());
rowNumber++;
dtrowNumber++;
}
// create 2 blank rows
for (int i = 0; i < 2; i++)
{
//Create a new Row
var row = sheet.CreateRow(rowNumber);
//Set cell Value
for (int cellnumber = 0; cellnumber < columncounter; cellnumber++)
row.CreateCell(cellnumber + 1).SetCellValue("");
rowNumber++;
}
// Add Date of extraction and source
var extractedDate = sheet.CreateRow(rowNumber);
var ecel = extractedDate.CreateCell(4);
ecel.SetCellValue("Extracted Date : ");
// ecel.CellStyle = hStyle;
extractedDate.CreateCell(5).SetCellValue(DateTime.Now.ToString("dd - MMM - yyyy"));
rowNumber++;
var Disclaimer = sheet.CreateRow(rowNumber);
var dcel = Disclaimer.CreateCell(4);
dcel.SetCellValue("Disclaimer : ");
// dcel.CellStyle = hStyle;
Disclaimer.CreateCell(5).SetCellValue("All Rights Reserved.");
rowNumber++;
var Disclaimer1 = sheet.CreateRow(rowNumber);
Disclaimer1.CreateCell(5).SetCellValue("Give some information at footer");
rowNumber++;
}
else
{
for (int i = 0; i <= 10; i++)
headerRow.CreateCell(i).SetCellValue("");
}
// End of add rows
//Write the Workbook to a memory stream
MemoryStream output = new MemoryStream();
workbook.Write(output);
return output;
}
you can download NPOI.Dll from this link
Download NPOI.dll
Hope this will solve your problem.
Related
I want to generate excel with Epplus C# on my WEB.
I want to create multi sheets in Excel with different content on each sheet.
I think maybe I have to use loop For.
but I do not know how to coding.
Please help me. Sorry for my bad english.
using (ExcelPackage pkg = new ExcelPackage())
{
var fullFilename = "warming up specification.xlsx";
var oldFilePath = Server.MapPath("~/File" + "/" + fullFilename);
using (FileStream stream = new FileStream(oldFilePath, FileMode.Open))
{
pkg.Load(stream);
ExcelWorksheet ws = pkg.Workbook.Worksheets[1];
//set Fixed Cell value
foreach (var item in dict)
{
ws.Cells[item.Key].Value = item.Value;
}
ws.Cells.Style.Font.Size = 13;
ws.Cells.Style.WrapText = true;
ws.PrinterSettings.PaperSize = ePaperSize.A4;
ws.PrinterSettings.FitToPage = true;
ws.PrinterSettings.FooterMargin = 0M;
ws.PrinterSettings.TopMargin = 0M;
ws.PrinterSettings.LeftMargin = 0M;
ws.PrinterSettings.RightMargin = 0M;
ws.Cells["A1:AC1"].Merge = true;
ws.Cells["A1:AC1"].Style.Font.Bold = true;
ws.Cells["A1:AC1"].Style.Font.Size = 25;
ws.Cells["A1:AC1"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells["A1:AC1"].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
ws.Cells["A1:AC1"].Value = "TEST";
// ws.Cells["F1:L1"].Style.Border.Bottom.Style = ws.Cells["F1:L1"].Style.Border.Left.Style = ws.Cells["F1:L1"].Style.Border.Right.Style = ws.Cells["F1:L1"].Style.Border.Top.Style = ExcelBorderStyle.Thin;
Random rand = new Random();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMdd") + "_" + rand.Next(1, 999) + "_" + fullFilename);
Response.BinaryWrite(pkg.GetAsByteArray());
Response.End();
}
If what you are looking for is multiple worksheets in same file then just add another worksheet.
ExcelWorksheet ws1 = pkg.Workbook.Worksheets.Add("WorkSheet1");
//your operations for worksheet1
ExcelWorksheet ws2 = pkg.Workbook.Worksheets.Add("WorkSheet2");
//your operations for worksheet2
I am exporting three worked sheet in single XL file, but I am missing some user data in the second DataTable (Education Details sheet) and third DataTable (Employeement Details sheet).
The Education Details sheet is some users are not there, but an Employeement Details sheet that users are showing. User Email Id's is there all three Database Tables.
DataSe ds = new DataSet();
DataTable dt = new DataTable("Registration Details");
DataTable dt1 = new DataTable("Education Details");
DataTable dt2 = new DataTable("Employeement Details");
dt = bl.Get_Registrationdetailsbydate(bo);
gv_Regdetails.DataSource = dt;
gv_Regdetails.DataBind();
dt1 = bl.Get_Registrationdetailsbydate1(bo);
dt2 = bl.Get_Registrationdetailsbydate2(bo);
DataTable filteredEducation = dt1.AsEnumerable()
.Where(x => dt.AsEnumerable()
.Any(z => z.Field<string>("Email").Trim() == x.Field<string>("Email").Trim()))
.CopyToDataTable();
DataTable filteredEmployee = dt2.AsEnumerable()
.Where(x => dt.AsEnumerable()
.Any(z => z.Field<string>("Email").Trim() == x.Field<string>("Email").Trim()))
.CopyToDataTable();
dt.TableName = "Registration Details";
filteredEducation.TableName = "Education Details";
filteredEmployee.TableName = "Employeement Details";
ds.Tables.Add(dt);
ds.Tables.Add(filteredEducation);
ds.Tables.Add(filteredEmployee);
ExcelHelper.ToExcel(ds, "DangoteUsers.xls", Page.Response);
I did result base on first DataTable users Email, then fill second DataTable detail users base on first DataTable Email id's. Same as Employment Details. The issue in first DataTable and second DataTable. I am not returning the DataTable also.
I refer this example
The problem is coming somewhere from the solution of conversion from DataSet to Excel in the article. Using this self made conversion is not a good idea. Use Jet/ACE engine or Microsoft Office Interop. At least they guarantee, they don't have such kind of bugs, which in future can became more. Better use something which is already highly accepted by the community. Here I wrote an approach how to do it with Interop.
First what you need to do is to add the reference to Microsoft.Office.Interop.Excel. Here is how to do it, taken from msdn article
Add the Excel assembly as a reference to the project: Right-click on
the project, select Add Reference.
Click the COM tab of the Add Reference dialog box, and find Microsoft
Excel 11 Object Library.
Double-click on Microsoft Excel 11 Object Library, and
press OK.
Obviously if you have bigger version of Excel 11 use it.
Here is the code, there are comments/regions with the workflow of it. You should use using Excel = Microsoft.Office.Interop.Excel; as reference
public void ExcelBtn_Click(object sender, EventArgs e)
{
DataSet dst = PrepareData();
byte[] bytes = ExportDataSetToExcel(dst);
Response.ClearContent();
Response.ContentType = "application/msoffice";
Response.AddHeader("Content-Disposition", #"attachment; filename=""ExportedExcel.xlsx"" ");
Response.BinaryWrite(bytes);
Response.End();
}
public static DataSet PrepareData()
{
DataTable badBoysDst = new DataTable("BadBoys");
badBoysDst.Columns.Add("Nr");
badBoysDst.Columns.Add("Name");
badBoysDst.Rows.Add(1, "Me");
badBoysDst.Rows.Add(2, "You");
badBoysDst.Rows.Add(3, "Pepe");
badBoysDst.Rows.Add(4, "Roni");
//Create a Department Table
DataTable goodBoysDst = new DataTable("GoodBoys");
goodBoysDst.Columns.Add("Nr");
goodBoysDst.Columns.Add("Name");
goodBoysDst.Rows.Add("1", "Not me");
goodBoysDst.Rows.Add("2", "Not you");
goodBoysDst.Rows.Add("3", "Quattro");
goodBoysDst.Rows.Add("4", "Stagioni");
DataTable goodBoysDst2 = new DataTable("GoodBoys2");
goodBoysDst2.Columns.Add("Nr");
goodBoysDst2.Columns.Add("Name");
goodBoysDst2.Rows.Add("1", "Not me");
goodBoysDst2.Rows.Add("2", "Not you");
goodBoysDst2.Rows.Add("3", "Quattro");
goodBoysDst2.Rows.Add("4", "Stagioni");
DataTable goodBoysDst3 = new DataTable("GoodBoys3");
goodBoysDst3.Columns.Add("Nr");
goodBoysDst3.Columns.Add("Name");
goodBoysDst3.Rows.Add("1", "Not me");
goodBoysDst3.Rows.Add("2", "Not you");
goodBoysDst3.Rows.Add("3", "Quattro");
goodBoysDst3.Rows.Add("4", "Stagioni");
//Create a DataSet with the existing DataTables
DataSet dst = new DataSet("SchoolBoys");
dst.Tables.Add(badBoysDst);
dst.Tables.Add(goodBoysDst);
dst.Tables.Add(goodBoysDst2);
dst.Tables.Add(goodBoysDst3);
return dst;
}
public static byte[] ExportDataSetToExcel(DataSet dst)
{
#region Create The Excel
Excel.Application excelApp = null;
Excel.Workbook excelWorkBook = null;
try
{
excelApp = new Excel.Application();
if (excelApp == null)
throw new Exception("You can throw custom exception here too");
excelWorkBook = excelApp.Workbooks.Add();
int sheetNr = 1;
foreach (DataTable table in dst.Tables)
{
Excel.Worksheet excelWorkSheet = null;
//Add a new worksheet or reuse first 3 sheets of workbook with the Datatable name
if (sheetNr <= excelWorkBook.Sheets.Count)
{
excelWorkSheet = excelWorkBook.Sheets.get_Item(sheetNr);
}
else
{
excelWorkSheet = excelWorkBook.Sheets.Add(After: excelWorkBook.Sheets[excelWorkBook.Sheets.Count]);
}
excelWorkSheet.Name = table.TableName;
for (int i = 1; i < table.Columns.Count + 1; i++)
{
excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
}
for (int j = 0; j < table.Rows.Count; j++)
{
for (int k = 0; k < table.Columns.Count; k++)
{
excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
}
}
sheetNr += 1;
}
//make first sheet active
excelApp.ActiveWorkbook.Sheets[1].Select();
excelWorkBook.SaveAs(#"c:\temp\DataSetToExcel.xlsx");
}
finally
{
excelWorkBook.Close();
excelApp.Quit();
//you should call GC here because there is memory problem with Interop
GC.Collect();
GC.WaitForPendingFinalizers();
}
#endregion
#region Take byte[] of the excel
byte[] result = null;
using (FileStream fs = new FileStream(#"c:\temp\DataSetToExcel.xlsx", FileMode.Open, FileAccess.Read))
{
BinaryReader reader = new BinaryReader(fs);
result = reader.ReadBytes((int)fs.Length);
}
#endregion
#region Delete the excel from the server
File.Delete(#"c:\temp\DataSetToExcel.xlsx");
#endregion
return result;
}
}
So try to use something established by the community already.This is pretty much full example how to do it with Interop. Personally I prefer to use ACE/JET engines, because there is no memory leaks problems like in the Interop(because of that we are calling the GC in the code). Creation of new sheets with ACE/JET engine is a little bit harder.
I think your string comparison in linq query is a problem..your email address might have different case which could have caused this issue. Try below code
DataTable filteredEducation = dt1.AsEnumerable()
.Where(x => dt.AsEnumerable()
.Any(z => z.Field<string>("Email").Trim().Equals(x.Field<string>("Email").Trim(),StringComparison.CurrentCultureIgnoreCase)))
.CopyToDataTable();
DataTable filteredEmployee = dt2.AsEnumerable()
.Where(x => dt.AsEnumerable()
.Any(z => z.Field<string>("Email").Trim().Equals(x.Field<string>("Email").Trim(),StringComparison.CurrentCultureIgnoreCase)))
.CopyToDataTable();
I had done the same export problem by manual export. First, i need to prepare a responce http responce properly, than add all headers(with rowsapn and colspan attributes) of your tables and then populate data:
//this fun is called after click on export button for example
public void Export(string fileName, GridView gv)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", String.Format("{0}.xls", fileName)));
HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "utf-8");
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.Write(#"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
HttpContext.Current.Response.Charset = "utf-8";//"windows-1251";//
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a table to contain the grid
Table table = new Table();
table.Width = Unit.Percentage(100);
// include the gridline settings
table.GridLines = gv.GridLines;
//header
TableRow r = new TableRow();
TableCell cell = new TableCell()
{
ColumnSpan = 18,
Text = fileName,
BackColor = Color.LightGray,
HorizontalAlign = HorizontalAlign.Center
};
cell.Font.Size = new FontUnit(14);
r.Cells.Add(cell);
table.Rows.Add(r);
GridViewRow row;
int rowSpan = 0;
//second row
row = CreateSecondHeaderRow();
table.Rows.AddAt(1, row);
//first row
row = CreateFirstHeaderRow(row, rowSpan);
table.Rows.AddAt(1, row);
// add each of the data rows to the table
for (int j = 0; j < gv.Rows.Count; j++)
{
//Set the default color
gv.Rows[j].BackColor = System.Drawing.Color.White;
for (int i = 0; i < gv.Rows[j].Cells.Count; i++)
{
gv.Rows[j].Cells[i].BackColor = System.Drawing.Color.White;
gv.Rows[j].Cells[i].Width = gv.Columns[i].ItemStyle.Width;
gv.Rows[j].Cells[i].Font.Size = gv.Columns[i].ItemStyle.Font.Size;
gv.Rows[j].Cells[i].Font.Bold = gv.Columns[i].ItemStyle.Font.Bold;
gv.Rows[j].Cells[i].Font.Italic = gv.Columns[i].ItemStyle.Font.Italic;
//aligh
if (i == 0)
{
gv.Rows[j].Cells[i].Style["text-align"] = "center";
}
else
{
gv.Rows[j].Cells[i].Style["text-align"] = "right";
}
//for alternate
if (j % 2 != 1) gv.Rows[j].Cells[i].BackColor = Color.LightSteelBlue;
}
table.Rows.Add(gv.Rows[j]);
}
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
}
catch (Exception ex)
{
this._hasError = true;
ShowError(ex);
}
}
private TableHeaderCell CreateHeaderCell(string text = null, int rowSpan = 0, int columnSpan = 0, Color backColor = default(Color), Color foreColor = default(Color))
{
if (object.Equals(backColor, default(Color))) backColor = Color.LightGray;
if (object.Equals(foreColor, default(Color))) foreColor = Color.Black;
return new TableHeaderCell
{
RowSpan = rowSpan,
ColumnSpan = columnSpan,
Text = text,
BackColor = backColor
};
}
private GridViewRow CreateFirstHeaderRow(GridViewRow row, int rowSpan)
{
row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableHeaderCell cell = CreateHeaderCell("Surplus %");
row.Controls.Add(cell);
cell = CreateHeaderCell("The date", columnSpan: 2);
row.Controls.Add(cell);
if (this.WithQuantity)
{
cell = CreateHeaderCell("Total Quantity", 2 + rowSpan, backColor: Color.Yellow);
row.Controls.Add(cell);
}
cell = CreateHeaderCell("Total Amount", 2 + rowSpan);
row.Controls.Add(cell);
cell = CreateHeaderCell("Has elapsed periods from start", columnSpan: (this.WithQuantity ? (SurplusUtil.TheColumnsNumbers * 2) : SurplusUtil.TheColumnsNumbers));
row.Controls.Add(cell);
if (this.WithQuantity)
{
cell = CreateHeaderCell("Quantity <br style='mso-data-placement:same-cell;' /> surplus", 2 + rowSpan, backColor: Color.Yellow);
row.Controls.Add(cell);
}
cell = CreateHeaderCell("Principal <br style='mso-data-placement:same-cell;' /> surplus", 2 + rowSpan);
row.Controls.Add(cell);
return row;
}
private GridViewRow CreateSecondHeaderRow()
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableHeaderCell cell = CreateHeaderCell("Period number", rowSpan: ((this.WithQuantity) ? 2 : 0));
row.Controls.Add(cell);
cell = CreateHeaderCell("from", rowSpan: ((this.WithQuantity) ? 2 : 0));
row.Controls.Add(cell);
cell = CreateHeaderCell("to", rowSpan: ((this.WithQuantity) ? 2 : 0));
row.Controls.Add(cell);
for (int i = 0; i < SurplusUtil.TheColumnsNumbers; i++)
{
cell = CreateHeaderCell(i.ToString(),
columnSpan: ((this.WithQuantity) ? 2 : 0),
backColor: System.Drawing.Color.FromArgb(198, 239, 206),
foreColor: System.Drawing.Color.FromArgb(0, 97, 0));
row.Controls.Add(cell);
}
return row;
}
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 am currently making a web application using epPlus along with it to save the current database to an excel file. That part is easy and working, but what I'm trying to do is create a pop up dialog box that will allow the client to select the directory they want to save the excel file to. Then use the path they've given me and use the SaveAs function in epPlus with the path they have selected.
The question is how do I go about getting the dialog box to work and getting the path? I've tried using Response and I can't seem to get that working. The problem is that the excel file is only an object until save is done, and I need the path to do the save. Ideas? here's my code.
protected void OnbtnSaveExcelFileClick(object sender, EventArgs e)
{
String FileName = "GamingRecords";
String FilePath = #"C:\....\";
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
try
{
using (var package = new ExcelPackage(flUploadLink.FileContent))
{
var worksheet = package.Workbook.Worksheets.Add("Games to Date - " + DateTime.Now.ToShortDateString());
worksheet.DefaultRowHeight = 22;
var headers = new[] { Constants.GameTitle, Constants.GameGenre, Constants.Price, Constants.Quantity };
for (var i = 1; i < headers.Count() + 1; i++)
worksheet.Cells[1, i].Value = headers[i - 1];
var game = new GameClass();
var list = game.FetchAll();
var rowNumber = 2;
foreach (var t in list)
{
worksheet.Cells[rowNumber, 1].Value = t.GameTitle;
worksheet.Cells[rowNumber, 2].Value = t.GameGenre;
worksheet.Cells[rowNumber, 3].Value = t.Price;
worksheet.Cells[rowNumber, 4].Value = t.Quantity;
rowNumber++;
}
for (var i = 1; i < worksheet.Dimension.End.Column; i++)
worksheet.Column(i).AutoFit();
package.Workbook.Properties.Title = "Games on Record";
package.Workbook.Properties.Author = "Kirk Rudzinski";
package.Workbook.Properties.Company = "Logistics+";
package.Save();
litExcelError.Visible = false;
}
}
catch (IOException)
{ litExcelError.Text = "Please close the file to make modifications"; }
}
Alright, just to clarify I figured out how to do it the way I was trying. For reference in case anyone runs into an error like this here is the code!
protected void OnbtnSaveExcelFileClick(object sender, EventArgs e)
{
try
{
using (var package = new ExcelPackage(flUploadLink.FileContent))
{
var worksheet = package.Workbook.Worksheets.Add("Games to Date - " + DateTime.Now.ToShortDateString());
worksheet.DefaultRowHeight = 22;
var headers = new[] { Constants.GameTitle, Constants.GameGenre, Constants.Price, Constants.Quantity };
for (var i = 1; i < headers.Count() + 1; i++)
worksheet.Cells[1, i].Value = headers[i - 1];
int rowNumber = 2;
foreach (GridViewRow row in grdGamingTable.Rows)
{
var index = row.RowIndex;
worksheet.Cells[rowNumber, 1].Value = grdGamingTable.Rows[index].Cells[2].Text;
worksheet.Cells[rowNumber, 2].Value = grdGamingTable.Rows[index].Cells[3].Text;
worksheet.Cells[rowNumber, 3].Value = Convert.ToInt16(grdGamingTable.Rows[index].Cells[4].Text);
worksheet.Cells[rowNumber, 4].Value = Convert.ToInt16(grdGamingTable.Rows[index].Cells[5].Text);
rowNumber++;
}
for (var i = 1; i < worksheet.Dimension.End.Column; i++)
worksheet.Column(i).AutoFit();
package.Workbook.Properties.Title = "Games on Record";
package.Save();
litExcelError.Visible = false;
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=GameRecords.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
}
}
catch (IOException)
{ litExcelError.Text = "Please close the file to make modifications"; }
}
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);
}