C# – NPOI Excel Generator
using System.Data; using System.IO; using NPOI; using NPOI.HSSF.UserModel; using NPOI.XSSF.UserModel; using NPOI.SS.UserModel; static void Main( string[] args ) { DataTable dt = … …; DataTableToExcelFile( dt, "Person", "Excel.xls" ); } static void DataTableToExcelFile( DataTable dt, string SheetName, string FileName ) { IWorkbook wb = new HSSFWorkbook(); ISheet ws; if (dt.TableName != string.Empty) { ws = wb.CreateSheet(dt.TableName); } else { ws = wb.CreateSheet(SheetName); } ws.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { ws.GetRow(0).CreateCell(i).SetCellValue( (dt.Columns[i].Caption != null) ? dt.Columns[i].Caption : dt.Columns[i].ColumnName ); } for (int i = 0; i < dt.Rows.Count; i++) { ws.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { ws.GetRow(i + 1).CreateCell(j).SetCellValue(dt.Rows[i][j].ToString()); } } for (int i = 0; i < dt.Columns.Count; i++) { ws.AutoSizeColumn(i); } FileStream file = new FileStream( FileName, FileMode.Create ); wb.Write(file); file.Close(); } |
Reference From Here.
Integrated with DataTable Helper.
C# – Custom Class Model Annotation ( System.Attribute ) for Prepare DataColumn ( System.Data ) from DataTable Column with Sequence