Table of contents
Commonly used Excel export methods
1. Use the Microsoft Office Interop Excel component to export Excel files
2. Use NPOI component to export Excel file
3. Use the EPPlus component to export Excel files
4. Use the ClosedXML component to export Excel files
Commonly used Excel export methods
In C#, commonly used Excel file export methods include:
-
Using the Microsoft Office Interop Excel Component: This is a way to create and edit Excel files using the Microsoft Excel application object model. It offers powerful features, but requires Microsoft Excel or the Microsoft Office suite to be installed.
-
Use NPOI components: NPOI is an open source component on the C#/.NET platform, which can read and write documents in Microsoft Office format, including Excel, Word and PowerPoint. Compared with the Interop Excel component, NPOI is more lightweight and does not need to depend on the Microsoft Excel application.
-
Using the EPPlus component: EPPlus is a free and open source component that can create and read Excel files. It provides some convenience methods for manipulating cell formatting, charts, formulas, and more. EPPlus supports .NET Framework 3.5 and above and does not need to depend on Microsoft Excel application.
-
Using the ClosedXML Component: ClosedXML is an easy-to-use open source component that can read, create, and modify Excel files. Similar to EPPlus, it also provides some convenient methods to manipulate Excel files. ClosedXML supports .NET Framework 4.0 and later.
The above are several commonly used methods of C# exporting Excel files. Each method has its own characteristics and advantages and disadvantages. Just choose the method that suits your needs for development. For each export method, specific steps and demos are listed below.
1. Use the Microsoft Office Interop Excel component to export Excel files
The steps to export an Excel file using the Microsoft Office Interop Excel component are as follows:
-
Reference the Microsoft.Office.Interop.Excel namespace: Add a reference to Microsoft.Office.Interop.Excel in your project, or install it using the NuGet package manager.
-
Create an Excel application object: Use
Application
the class to create an Excel application object. -
Create workbook object: Use
Application.Workbooks.Add()
the method to create a new workbook object. -
Get sheet object: Use
Workbook.Worksheets
the property to get the sheet collection, and use the index or name to get the sheet object. -
Write data to the cell: Use
Worksheet.Cells
the property to get the cell object, and useRange.Value
the property orRange.Formula
property to write data to the cell. -
Save Excel file: Use
Workbook.SaveAs()
the method to save an Excel file to disk. -
Close the Excel application and workbook objects: use
Workbook.Close()
the method to close the workbook object, and useApplication.Quit()
the method to close the Excel application object. -
Release resources: Use
Marshal.ReleaseComObject()
the method to release the resources of the Excel application object and workbook object.
Here is a sample code that demonstrates how to export an Excel file using the Microsoft Office Interop Excel component:
using System;
using System.Data;
using System.IO;
using Microsoft.Office.Interop.Excel;namespace ExportExcelDemo
{ class Program { static void Main(string[] args) { // Create a DataTable object to store data DataTable dataTable = new DataTable("MyData");
// 添加列到 DataTable
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Age", typeof(int));// Add data rows to DataTable
dataTable.Rows.Add("John Doe", 30);
dataTable.Rows.Add("Jane Smith", 25);// 使用 Microsoft Office Interop Excel 组件导出 Excel 文件
Application excelApp = new Application();
Workbook workbook = excelApp.Workbooks.Add();
Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
int row = 1;
foreach (DataRow dataRow in dataTable.Rows)
{
worksheet.Cells[row, 1] = dataRow["Name"].ToString();
worksheet.Cells[row, 2] = dataRow["Age"];
row++;
}// Save Excel file to disk
string fileName = @"C:\temp\MyExcelFile.xlsx";
workbook.SaveAs(fileName);// Close the Excel application and workbook object, and release resources
workbook.Close();
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook );
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}
}
}
In this sample code, we use Application
the class to create an Excel application object and use it to create a new workbook object. We then used Workbook.Worksheets
the property to get the sheet collection and used the index to get the first sheet object. Next, we Worksheet.Cells
get the cell object using the property and write data to the cell using Range.Value
the or property. Range.Formula
Finally, we Workbook.SaveAs()
save the Excel file to disk using the method, close the workbook object and the Excel application object, and release their resources.
2. Use NPOI component to export Excel file
The steps to export Excel files using NPOI components are as follows:
-
Reference the NPOI namespace: Add a reference to NPOI in your project, or install it using the NuGet package manager.
-
Create Workbook Object: Use
HSSFWorkbook
the orXSSFWorkbook
class to create a new workbook object, corresponding to Excel's .xls and .xlsx formats, respectively. -
Get worksheet object: use
CreateSheet()
the method to create a new worksheet object and set the worksheet name. -
Setting Cell Styles: You can use
CellStyle
the class andFont
class to set cell styles. -
Write data to a cell: use
CreateRow()
the method to create a new row object, useCreateCell()
the method to create a new cell object, and useSetValue()
the method to write data to the cell. -
Save Excel file: Use
FileStream
the class to save an Excel file to disk. -
Release resources: Use
Dispose()
the method to release the resources of the Workbook object and the FileStream object.
Below is a sample code that demonstrates how to export an Excel file using the NPOI component:
using System;
using System.Data;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;namespace ExportExcelDemo
{ class Program { static void Main(string[] args) { // Create a DataTable object to store data DataTable dataTable = new DataTable("MyData");
// 添加列到 DataTable
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Age", typeof(int));// Add data rows to DataTable
dataTable.Rows.Add("John Doe", 30);
dataTable.Rows.Add("Jane Smith", 25);// 使用 NPOI 组件导出 Excel 文件
IWorkbook workbook = new HSSFWorkbook();
ISheet worksheet = workbook.CreateSheet("MySheet");
int row = 0;
foreach (DataRow dataRow in dataTable.Rows)
{
IRow newRow = worksheet.CreateRow(row);
newRow.CreateCell(0).SetCellValue(dataRow["Name"].ToString());
newRow.CreateCell(1).SetCellValue(Convert.ToInt32(dataRow["Age"]));
row++;
}// Save the Excel file to disk
string fileName = @"C:\temp\MyExcelFile.xls";
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{ workbook.Write(fs); }// release resources
workbook.Dispose();
}
}
}
In this sample code, we use HSSFWorkbook
the class to create a new workbook object and use it to create a worksheet object named "MySheet". We then created new row objects and cell objects using CreateRow()
the method and method, and wrote data to the cell using the method. Finally, we use the class to save the Excel file to disk and the method to release the workbook object's resources. If you need to generate a file in .xlsx format, you can use the class instead of the class .CreateCell()
SetValue()
FileStream
Dispose()
XSSFWorkbook
HSSFWorkbook
3. Use the EPPlus component to export Excel files
The steps to export an Excel file using the EPPlus component are as follows:
-
Reference the EPPlus namespace: Add a reference to EPPlus in your project, or install it using the NuGet package manager.
-
Create Workbook Object: Use
ExcelPackage
the class to create a new workbook object. -
Get worksheet object: use
Workbook.Worksheets.Add()
the method to create a new worksheet object and set the worksheet name. -
Set cell style: You can use
ExcelRange.Style
the property to set the cell style. -
Write data to the cell: use
SetValue()
the method to write data to the cell. -
Save Excel file: Use
ExcelPackage.SaveAs()
the method to save an Excel file to disk. -
Release resources: use
Dispose()
the method to release the resources of the workbook object.
Below is a sample code that demonstrates how to export an Excel file using the EPPlus component:
using System;
using System.Data;
using System.IO;
using OfficeOpenXml;namespace ExportExcelDemo
{ class Program { static void Main(string[] args) { // Create a DataTable object to store data DataTable dataTable = new DataTable("MyData");
// 添加列到 DataTable
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Age", typeof(int));// Add data rows to DataTable
dataTable.Rows.Add("John Doe", 30);
dataTable.Rows.Add("Jane Smith", 25);// 使用 EPPlus 组件导出 Excel 文件
using (ExcelPackage excelPackage = new ExcelPackage())
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("MySheet");
int row = 1;
foreach (DataRow dataRow in dataTable.Rows)
{
worksheet.Cells[row, 1].Value = dataRow["Name"].ToString();
worksheet.Cells[row, 2].Value = Convert.ToInt32(dataRow["Age"]);
row++;
}// Save the Excel file to disk
string fileName = @"C:\temp\MyExcelFile.xlsx";
FileInfo fileInfo = new FileInfo(fileName);
excelPackage.SaveAs(fileInfo);
}// release resource
}
}
}
In this sample code, we use ExcelPackage
the class to create a new workbook object and use it to create a worksheet object named "MySheet". We then use Cells
the property to get the cell object and use SetValue()
the method to write data to the cell. Finally, we use ExcelPackage.SaveAs()
the method to save the Excel file to disk and Dispose()
the method to release the workbook object's resources.
4. Use the ClosedXML component to export Excel files
The steps to export an Excel file using the ClosedXML component are as follows:
-
Reference the ClosedXML namespace: Add a reference to ClosedXML in your project, or install it using the NuGet package manager.
-
Create Workbook Object: Use
XLWorkbook
the class to create a new workbook object. -
Get worksheet object: use
AddWorksheet()
the method to create a new worksheet object and set the worksheet name. -
Set cell style: You can use
IXLStyle
interface andIXLFont
interface to set cell style. -
Write data to the cell: use
SetValue()
the method to write data to the cell. -
Save Excel file: Use
SaveAs()
the method to save an Excel file to disk. -
Release resources: use
Dispose()
the method to release the resources of the workbook object.
Here is a sample code that demonstrates how to use the ClosedXML component to export an Excel file:
using System;
using System.Data;
using System.IO;
using ClosedXML.Excel;namespace ExportExcelDemo
{ class Program { static void Main(string[] args) { // Create a DataTable object to store data DataTable dataTable = new DataTable("MyData");
// 添加列到 DataTable
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Age", typeof(int));// Add data rows to DataTable
dataTable.Rows.Add("John Doe", 30);
dataTable.Rows.Add("Jane Smith", 25);// 使用 ClosedXML 组件导出 Excel 文件
using (XLWorkbook workbook = new XLWorkbook())
{
IXLWorksheet worksheet = workbook.AddWorksheet("MySheet");
int row = 1;
foreach (DataRow dataRow in dataTable.Rows)
{
worksheet.Cell(row, 1).Value = dataRow["Name"].ToString();
worksheet.Cell(row, 2).Value = Convert.ToInt32(dataRow["Age"]);// Set cell style
worksheet.Cell(row, 2).Style.Font.Bold = true;
worksheet.Cell(row, 2).Style.Alignment.Horizontal = XLAligmentHorizontalValues.Right;row++;
}// Save the Excel file to disk
string fileName = @"C:\temp\MyExcelFile.xlsx";
workbook.SaveAs(fileName);
}// release resource
}
}
}
In this sample code, we use XLWorkbook
the class to create a new workbook object and use it to create a worksheet object named "MySheet". Then, we use Cell()
the method to get the cell object, and use SetValue()
the method to write data to the cell. Next, we use IXLStyle
the interface and IXLFont
interface to set the cell style. Finally, we use SaveAs()
the method to save the Excel file to disk and Dispose()
the method to release the workbook object's resources.