Downloading Excel file after creating using EPPlus - c#

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/

Related

How to add multiple worksheets in workbook C#

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

How to generate Excel epplus C# new sheet with different content in each sheet

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

Export object to .xlsx to client machine asp.net core

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/

Add Company logo in top of the excel

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.

Trying to get Filepath with Open Dialog

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"; }
}

Categories

Resources