C# How to export DataTable to Excel solution
Recently, because the company project required all logs of user operations in the system to be transferred and backed up, and considering that they may need to be restored in the future, we finally decided to back up the log data to Excel.
The following is all the code of the Excel.cs class in my project. Through this class, the data in the DataTable can be easily imported into the Excel method.
First of all, you must download the NPOI.dll assembly.
The 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> /// 实例方法 /// </summary> /// <param name="sheetRowNum">单个表单允许的最大行数</param> public Excel(int sheetRowNum) { _sheetRowNum = sheetRowNum; InstanceWorkBook(); } /// <summary> /// 实例方法 /// </summary> /// <param name="columns">表头</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 small demo reference:
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 When the amount of data to be imported into Excel is large (hundreds of thousands or millions of rows), putting it all into the DataTable at once may consume a lot of memory. It is recommended that the data imported each time should not exceed 1,000 pieces. Import data into Excel using paging query.
Advantages: Each form in the 1997-2003 version of xls only supports a maximum of 65536 rows, and 2010 can support 1048576 rows. Considering that the versions installed on the client are different, each Excel object form supports a maximum of 65536 rows. , when the form reaches the maximum number of rows, a new form will be automatically created inside the Excel object. You don’t need to consider this when writing data to Excel, which is more convenient when calling.
For more C# related articles on how to export DataTable to Excel solutions, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.
