Several common ways and implementation steps of C# commonly used Excel export

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:

  1. 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.

  2. 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.

  3. 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.

  4. 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:

  1. 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.

  2. Create an Excel application object: Use Applicationthe class to create an Excel application object.

  3. Create workbook object: Use Application.Workbooks.Add()the method to create a new workbook object.

  4. Get sheet object: Use Workbook.Worksheetsthe property to get the sheet collection, and use the index or name to get the sheet object.

  5. Write data to the cell: Use Worksheet.Cellsthe property to get the cell object, and use Range.Valuethe property or Range.Formulaproperty to write data to the cell.

  6. Save Excel file: Use Workbook.SaveAs()the method to save an Excel file to disk.

  7. Close the Excel application and workbook objects: use Workbook.Close()the method to close the workbook object, and use Application.Quit()the method to close the Excel application object.

  8. 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 Applicationthe class to create an Excel application object and use it to create a new workbook object. We then used Workbook.Worksheetsthe property to get the sheet collection and used the index to get the first sheet object. Next, we Worksheet.Cellsget the cell object using the property and write data to the cell using Range.Valuethe or property. Range.FormulaFinally, 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:

  1. Reference the NPOI namespace: Add a reference to NPOI in your project, or install it using the NuGet package manager.

  2. Create Workbook Object: Use HSSFWorkbookthe or XSSFWorkbookclass to create a new workbook object, corresponding to Excel's .xls and .xlsx formats, respectively.

  3. Get worksheet object: use CreateSheet()the method to create a new worksheet object and set the worksheet name.

  4. Setting Cell Styles: You can use CellStylethe class and Fontclass to set cell styles.

  5. Write data to a cell: use CreateRow()the method to create a new row object, use CreateCell()the method to create a new cell object, and use SetValue()the method to write data to the cell.

  6. Save Excel file: Use FileStreamthe class to save an Excel file to disk.

  7. 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 HSSFWorkbookthe 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()FileStreamDispose()XSSFWorkbookHSSFWorkbook

 3. Use the EPPlus component to export Excel files

The steps to export an Excel file using the EPPlus component are as follows:

  1. Reference the EPPlus namespace: Add a reference to EPPlus in your project, or install it using the NuGet package manager.

  2. Create Workbook Object: Use ExcelPackagethe class to create a new workbook object.

  3. Get worksheet object: use Workbook.Worksheets.Add()the method to create a new worksheet object and set the worksheet name.

  4. Set cell style: You can use ExcelRange.Stylethe property to set the cell style.

  5. Write data to the cell: use SetValue()the method to write data to the cell.

  6. Save Excel file: Use ExcelPackage.SaveAs()the method to save an Excel file to disk.

  7. 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 ExcelPackagethe class to create a new workbook object and use it to create a worksheet object named "MySheet". We then use Cellsthe 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:

  1. Reference the ClosedXML namespace: Add a reference to ClosedXML in your project, or install it using the NuGet package manager.

  2. Create Workbook Object: Use XLWorkbookthe class to create a new workbook object.

  3. Get worksheet object: use AddWorksheet()the method to create a new worksheet object and set the worksheet name.

  4. Set cell style: You can use IXLStyleinterface and IXLFontinterface to set cell style.

  5. Write data to the cell: use SetValue()the method to write data to the cell.

  6. Save Excel file: Use SaveAs()the method to save an Excel file to disk.

  7. 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 XLWorkbookthe 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 IXLStylethe interface and IXLFontinterface 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. 

Guess you like

Origin blog.csdn.net/beenles/article/details/129954858