使用简易代码在 C# 中读取 Excel

发布: (2025年12月29日 GMT+8 11:32)
3 min read
原文: Dev.to

Source: Dev.to

Introduction

在日常的 C# 开发中,处理 Excel 数据几乎是每个开发者都会遇到的需求。无论是导入用户数据、生成报表,还是进行数据分析,Excel 都扮演着不可或缺的角色。传统的 C# Excel 读取方式——比如基于 COM Interop 的 Microsoft.Office.Interop.Excel——常常受到性能瓶颈、环境依赖以及部署复杂等问题的困扰。

本文展示了如何使用 Spire.XLS(适用于 .NET)实现一个简洁、高效的 Excel 读取方案,且无需任何 Office 依赖。

Environment Preparation

Step 1: Create a VS2022 Console Project

  • File → New → Project → Console App 模板。

Step 2: Install via NuGet

  • Graphic Interface: 右键项目 → Manage NuGet Packages → 搜索 FreeSpire.XLS

  • Command Line:

    Install-Package Spire.XLS
    # or the free version
    Install-Package FreeSpire.XLS

通过确认 Spire.XLS 程序集出现在项目引用中来验证安装是否成功。

Read Excel Files in C# Quickly

Import the Namespace

using Spire.Xls;

Read Individual Cells

// Load Excel (supports both XLS and XLSX formats)
Workbook wb = new Workbook();
wb.LoadFromFile("Sample.xlsx");

// Read cell data (2 methods)
Worksheet sheet = wb.Worksheets[0];
Console.WriteLine(sheet.Range["A1"].Value);      // Locate by column name
Console.WriteLine(sheet.Range[2, 1].Value);      // Locate by row and column numbers

Common Pitfall: 当按行列号读取数据时,索引从 1 开始,而不是 0。

Read Data from an Entire Worksheet

using Spire.Xls;

namespace ReadExcelData
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the Excel document
            Workbook wb = new Workbook();
            wb.LoadFromFile("Sample.xlsx");

            // Get the first worksheet
            Worksheet sheet = wb.Worksheets[0];

            // Get the data range in the worksheet
            CellRange locatedRange = sheet.AllocatedRange;

            // Iterate through rows and columns in the range
            for (int i = 0; i < locatedRange.Rows.Length; i++)
            {
                for (int j = 0; j < locatedRange.Rows[i].ColumnCount; j++)
                {
                    // Read cell data
                    Console.Write(locatedRange[i + 1, j + 1].Value + "  ");
                }
                Console.WriteLine();
            }
        }
    }
}

Read Excel Formulas

Value 属性返回的是公式本身。若要获取计算后的结果,请使用 FormulaValue

foreach (CellRange cell in sheet.AllocatedRange)
{
    if (cell.HasFormula)
    {
        // Original formula
        string formula = cell.Formula;

        // Calculated result of the formula
        string formulaResult = cell.FormulaValue.ToString();
    }
}

在 C# 中读取 Excel 文件是一个常见任务。选择合适的工具——如 Spire.XLS——可以显著提升开发效率和程序的稳定性。

Back to Blog

相关文章

阅读更多 »

在 C# 中将 RTF 转换为 PDF

概述 RTF(Rich Text Format)是一种跨平台的格式,广泛用于文档编辑和数据交换。相比之下,PDF 则是文档分发的理想选择……