C how do I export DataTable to Excel solution

  • 2020-05-07 20:21:16
  • OfStack

Recently, due to the need to transfer and backup all logs operated by users in the system in the company's project, it was finally decided to backup the log data to Excel considering that it may need to be restored in the future.

Here is all the code for the Excel.cs class in my project, which makes it easy to import data from DataTable into the Excel method.

First, you must download the NPOI.dll assembly,
Class code is as follows:
 
using System; 
using NPOI.HSSF; 
using NPOI.HPSF; 
using NPOI.HSSF.UserModel; 
using NPOI.HSSF.Util; 
using NPOI.SS.UserModel; 
using System.Collections; 
using System.IO; 
using System.Data; 
namespace BackupAttach 
{ 
public class Excel 
{ 
private HSSFWorkbook _workBook; 
private ISheet _wbSheet = null; 
private DataColumnCollection _columns = null; 
private int _col = 0; //total columns 
private int _row = 0; //total rows 
private int _sheet = 0; //total sheets 
private int _sheetRowNum = 65536; //each sheet allow rows 
public Excel() 
{ 
InstanceWorkBook(); 
} 
/// <summary> 
///  Instance methods  
/// </summary> 
/// <param name="sheetRowNum"> The maximum number of rows allowed for a single form </param> 
public Excel(int sheetRowNum) 
{ 
_sheetRowNum = sheetRowNum; 
InstanceWorkBook(); 
} 
/// <summary> 
///  Instance methods  
/// </summary> 
/// <param name="columns"> header </param> 
public Excel(DataColumnCollection columns) 
{ 
_columns = columns; 
InstanceWorkBook(); 
} 
private void InstanceWorkBook() 
{ 
/////cretate WorkBook 
_workBook = new HSSFWorkbook(); 
var dsi = PropertySetFactory.CreateDocumentSummaryInformation(); 
dsi.Company = "BaiyiTimes"; 
_workBook.DocumentSummaryInformation = dsi; 
////create a entry of SummaryInformation 
var si = PropertySetFactory.CreateSummaryInformation(); 
si.Subject = "Etimes Secure Document System Log Backup"; 
_workBook.SummaryInformation = si; 
} 
private DataColumnCollection GetColumns(DataColumnCollection columns) 
{ 
return columns == null || columns.Count == 0 ? _columns : columns; 
} 
private ISheet GetSheet(ISheet sheet) 
{ 
return sheet == null ? _wbSheet : sheet; 
} 
private void CreateHeader(ISheet sheet, DataColumnCollection columns) 
{ 
_columns = GetColumns(columns); 
/////create row of column 
var oRow = sheet.CreateRow(0); 
foreach (DataColumn column in _columns) 
{ 
var oCell = oRow.CreateCell(_col); 
var style1 = _workBook.CreateCellStyle(); 
style1.FillForegroundColor = HSSFColor.BLUE.index2; 
style1.FillPattern = FillPatternType.SOLID_FOREGROUND; 
style1.Alignment = HorizontalAlignment.CENTER; 
style1.VerticalAlignment = VerticalAlignment.CENTER; 
var font = _workBook.CreateFont(); 
font.Color = HSSFColor.WHITE.index; 
style1.SetFont(font); 
oCell.CellStyle = style1; 
var name = column.ColumnName; 
oCell.SetCellValue(name.ToString()); 
_col++; 
} 
///// header belong to rows 
_row++; 
} 
private void CreateHeader(ISheet sheet) 
{ 
CreateHeader(sheet, null); 
} 
public ISheet CreateSheet() 
{ 
return CreateSheet(null); 
} 
public ISheet CreateSheet(DataColumnCollection columns) 
{ 
_wbSheet = _workBook.CreateSheet((_sheet + 1).ToString()); 
CreateHeader(_wbSheet, columns); 
_sheet++; 
return _wbSheet; 
} 
public void SetRowValue(DataRowCollection rows, ISheet sheet) 
{ 
_wbSheet = GetSheet(sheet); 
foreach (DataRow row in rows) 
{ 
SetRowValue(row); 
} 
} 
public void SetRowValue(DataRowCollection rows) 
{ 
SetRowValue(rows, null); 
} 
public void SetRowValue(DataRow row) 
{ 
// create a new sheet 
if (_row % _sheetRowNum == 0) 
{ 
CreateSheet(); 
} 
var oRow = _wbSheet.CreateRow(_row % _sheetRowNum); 
var obj = string.Empty; 
var cell = 0; 
foreach (DataColumn column in _columns) 
{ 
obj = row[column.ColumnName].ToString(); 
oRow.CreateCell(cell).SetCellValue(obj); 
cell++; 
} 
_row++; 
} 
public void SetProtectPassword(string password, string username) 
{ 
_workBook.WriteProtectWorkbook(password, username); 
} 
public void SaveAs(string filePath) 
{ 
if (File.Exists(filePath)) File.Delete(filePath); 
var file = new FileStream(filePath, FileMode.Create); 
_workBook.Write(file); 
file.Close(); 
} 
} 
} 

The following is a common reference for little Demo:
 
public void DataTableToExcel(DataTable dt,string path) 
{ 
//instance excel object 
//Excel excel = new Excel(65536); 
Excel excel = new Excel(); 
//create a sheet 
excel.CreateSheet(dt.Columns); 
//write value into rows 
//excel.SetRowValue(dt.Rows); 
foreach (DataRow row in dt.Rows) 
{ 
excel.SetRowValue(row); 
} 
// set excel protected 
excel.SetProtectPassword("etimes2011@", "baiyi"); 
// save excel file to local 
excel.SaveAs(path); 
} 

disadvantages : if you want to import a large amount of data into Excel (several hundred thousand or millions of rows), all the time into DataTable may be a big memory consumption, it is recommended that the imported data at a time is best not more than 1000 pieces, you can take the method of paging query to import the data into Excel.

advantages : 1997-2003 version of the xls each form the largest support only 65536 lines, 2010 can support 1048576 lines, considering the version installed on the client not 1 sample, so the Excel object each form support 65536 lines maximum, when the form reaches the maximum number of lines, Excel inside the object will automatically create a new form, writing the data in the Excel don't consider this 1 point, so when the call is more convenient

Related articles: