Featured
ASP.NET free library for reading, manipulating and writing Excel - ClosedXML
Last modified: April 07, 2022- Create a MVC application
- Install the Closed_XML package
private ClosedXML.Excel.XLWorkbook GenerateClosedXMLWorkbook()
{
var wb = new ClosedXML.Excel.XLWorkbook();
var ws = wb.AddWorksheet();
ws.FirstCell().SetValue("Hello world!");
ws.FirstCell().CellBelow().FormulaA1 = "RAND()";
return wb;
}
Save
string path = "C:\\Temp\\Excel\\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
using (var wb = GenerateClosedXMLWorkbook())
{
wb.SaveAs(path + "test.xlsx");
}
Download
using (var wb = GenerateClosedXMLWorkbook())
{
return wb.Deliver("generatedfile.xlsx");
}
Read
var dt = new DataTable();
dt.Columns.Add("Col1");
var filePath = "C:\\Temp\\Excel\\test.xlsx";
using (var workBook = new XLWorkbook(filePath))
{
var workSheet = workBook.Worksheet(1);
foreach (IXLRow row in workSheet.Rows())
{
int i = 0;
dt.Rows.Add();
foreach (IXLCell cell in row.Cells())
{
dt.Rows[dt.Rows.Count - 1][i] = cell.Value.ToString();
i++;
}
}
}