Keywords: C# | Excel Export | List Data
Abstract: This article explores multiple methods for exporting list data to Excel files in C# applications. It focuses on the official approach using Excel Interop (COM), which requires Microsoft Excel installation, detailing steps such as creating application instances, workbooks, and worksheets, then iterating through the list to write data into cells. The article also supplements this with alternative methods using the ClosedXML library, which does not require Excel installation and offers a simpler API, as well as quick approaches like CSV export and the ArrayToExcel library. Each method is explained with code examples and procedural guidance, helping developers choose the appropriate technology based on project needs.
Introduction
In software development, exporting data from in-memory structures like lists to Excel files is a common requirement, especially for report generation, data analysis, and user interaction scenarios. C#, as a widely used programming language, offers various ways to achieve this, ranging from official interfaces dependent on Microsoft Office to lightweight third-party library solutions. Based on high-scoring answers from Stack Overflow, this article systematically introduces these methods, helping developers understand their core principles, advantages, disadvantages, and applicable contexts.
Using Excel Interop (COM) Method
Excel Interop is the official COM interface provided by Microsoft, allowing programmatic control of the Excel application. This method requires Microsoft Excel to be installed on the target system and is suitable for scenarios needing deep integration with Excel or leveraging its advanced features.
First, add a reference to Microsoft.Office.Interop.Excel in your Visual Studio project. Select the appropriate assembly based on your Visual Studio and Excel versions. Here is a complete example code demonstrating how to export a list of strings to Excel:
using NsExcel = Microsoft.Office.Interop.Excel;
public void ListToExcel(List<string> list)
{
// Start the Excel application
NsExcel.ApplicationClass excapp = new NsExcel.ApplicationClass();
excapp.Visible = true; // Optional: make the Excel window visible
// Create a new workbook
var workbook = excapp.Workbooks.Add(NsExcel.XlWBATemplate.xlWBATWorksheet);
// Get the first worksheet (indexing starts from 1)
var sheet = (NsExcel.Worksheet)workbook.Sheets[1];
// Iterate through the list and write data to column A
int counter = 1;
foreach (var item in list)
{
string cellName = "A" + counter.ToString();
var range = sheet.get_Range(cellName, cellName);
range.Value2 = item.ToString();
++counter;
}
// Save the workbook (omitted in example; in practice, call workbook.SaveAs)
// workbook.SaveAs(@"C:\output.xlsx");
// workbook.Close();
// excapp.Quit();
}Key points include: using ApplicationClass to start Excel, creating a new workbook via Workbooks.Add, and writing data with get_Range and the Value2 property. Note that Excel Interop may cause performance issues or resource leaks, so it is essential to properly release objects after use (e.g., by calling Quit).
Using the ClosedXML Library
For scenarios where Excel installation is not required, ClosedXML is a popular open-source library based on the Open XML SDK, offering a concise API to create and manipulate Excel files. This method is more lightweight and has better cross-platform compatibility.
After installing the ClosedXML library via NuGet Package Manager or direct assembly reference, here is a basic example:
using ClosedXML.Excel;
public void ListToExcelWithClosedXML(List<string> list)
{
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("DataSheet");
int row = 1;
foreach (var item in list)
{
ws.Cell("A" + row).Value = item.ToString();
row++;
}
workbook.SaveAs("output.xlsx");
}ClosedXML also supports advanced features, such as directly inserting data tables: ws.Cell(1, 1).InsertTable(dataList);, which automatically handles column headers and formatting. Compared to Excel Interop, ClosedXML does not require Excel installation, reducing deployment complexity, but it may lack some advanced Excel features.
Additional Methods
Beyond the two main methods, other quick solutions include:
- CSV Export: If the data format is simple, you can export the list as a CSV file, which Excel can open directly. Example code:
This approach is lightweight and fast but lacks Excel's formatting and formula support.using System.IO; using (StreamWriter sw = File.CreateText("list.csv")) { foreach (var item in list) { sw.WriteLine(item); } } - ArrayToExcel Library: This library is designed specifically for arrays or lists, offering a minimalistic API. Example:
It is suitable for rapid prototyping but may have limited community support and features.byte[] excel = list.ToExcel(); File.WriteAllBytes("result.xlsx", excel);
Performance and Selection Recommendations
When choosing a method, consider the following factors:
- Dependencies: Excel Interop requires Microsoft Excel installation, making it suitable for enterprise environments; ClosedXML and CSV methods do not require installation, better fitting cloud or cross-platform applications.
- Feature Requirements: If advanced Excel features like macros or charts are needed, Excel Interop is the preferred choice; for basic data export, ClosedXML or CSV is sufficient.
- Performance: Excel Interop can be slower and prone to resource leaks; ClosedXML, based on file operations, is generally faster; CSV is the most lightweight option.
- Code Maintenance: ClosedXML provides a more modern API, easier to maintain; Excel Interop code can be more verbose.
Based on Stack Overflow answer scores, Excel Interop (score 10.0) and ClosedXML (score 10.0) are the most recommended methods, representing benchmarks for official and third-party solutions, respectively.
Conclusion
Exporting list data to Excel in C# can be achieved through various methods, from official Excel Interop to lightweight ClosedXML, each with its applicable scenarios. Developers should select the appropriate method based on project requirements, environmental constraints, and feature needs. The code examples and comparative analysis provided in this article aim to help readers quickly get started and make informed decisions. In practice, testing is recommended to evaluate performance and compatibility, ensuring a stable and efficient export process.