search
HomeBackend DevelopmentC#.Net TutorialC# 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!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment