Write content from ASP.NET to Excel
To write the content of a GridView to an Excel file and save it to a desired location using the FileStream class in ASP.NET, you can follow the steps below:
Create a new Excel package using the EPPlus library (ensure that the EPPlus NuGet package is installed in your project):
using OfficeOpenXml;
// Create a new Excel package
ExcelPackage excelPackage = new ExcelPackage();
Get the GridView data and populate it into an Excel worksheet:
// Get the GridView data
GridView gridView = new GridView();
gridView.DataSource = // Your data source;
gridView.DataBind();
// Create a new worksheet in the Excel package
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet1");
// Populate the worksheet with GridView data
for (int i = 0; i < gridView.Rows.Count; i++)
{
for (int j = 0; j < gridView.Columns.Count; j++)
{
worksheet.Cells[i + 1, j + 1].Value = gridView.Rows[i].Cells[j].Text;
}
}
Save the Excel package to a desired location using the FileStream class:
// Specify the file path and name
string filePath = "desired_location\\file_name.xlsx";
// Save the Excel package to the specified location using FileStream
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
excelPackage.SaveAs(fileStream);
}
Make sure to replace "desired_location" with the desired directory path and "file_name.xlsx" with the desired file name.
This code will write the content of the GridView to an Excel file and save it to the specified location using the FileStream class.
Related Topics