Tuesday, 7 March 2017

Generate XLSX File using NPOI in c#.


//Add References
NPOI.dll
NPOI.OOXML.dll
NPOI.OpenXml4Net.dll
NPOI.OpenXmlFormats.dll

//Add Library --
using NPOI.XSSF.UserModel;

public void GenerateXLSFileNPOI(DataTable _dt)
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sh = new XSSFSheet();

wb = new XSSFWorkbook();

// create sheet
sh = (XSSFSheet)wb.CreateSheet("Sheet1");

//Add Header Row
var r0 = sh.CreateRow(0);
//Add Header in Row From The Datatable
for (int j = 0; j < _dt.Columns.Count; j++)
{
r0.CreateCell(j);
sh.GetRow(0).GetCell(j).SetCellValue(_dt.Columns[j].ToString());
}

//Data Add In Rows From The DataTable
for (int i = 0; i < _dt.Rows.Count; i++)
{
var r = sh.CreateRow(i + 1);
for (int j = 0; j < _dt.Columns.Count; j++)
{
r.CreateCell(j);
sh.GetRow(i + 1).GetCell(j).SetCellValue(_dt.Rows[i][j].ToString());
}
}

//Finaly Write Data InTo Xlsx File
using (var fs = new FileStream("test.xlsx", FileMode.Create, FileAccess.Write))
{
wb.Write(fs);
}
}

No comments:

Post a Comment