C#基础:用ClosedXML实现Excel读取

直接在控制台程序输出,注意该程序需要添加Nuget包:

using System;
using System.Collections.Generic;
using ClosedXML.Excel;

class Program
{
    static void Main(string[] args)//需要先安装Nuget包:ClosedXML.Excel
    {
        // Excel 文件路径
        string filePath = @"F:\C_program\test2\files\工作表.xlsx";

        // 工作表名称
        string sheetName = "Sheet1";

        // 获取整个表格的数据
        List dataList = ReadExcelWithClosedXML(filePath, sheetName).Where(x=>!string.IsNullOrEmpty(x)).ToList();

        // 获取第2行的数据
        List rowList = ReadExcelWithClosedXML(filePath, sheetName, "Row", 2).Where(x => !string.IsNullOrEmpty(x)).ToList();

        // 获取B列的数据
        List columnList = ReadExcelWithClosedXML(filePath, sheetName, "Column", 2).Where(x => !string.IsNullOrEmpty(x)).ToList();
        
    }

    static List ReadExcelWithClosedXML(string filePath, string sheetName, string type = null, int num = 0)
    {
        // 存储 Excel 数据的列表
        List dataList = new List();

        // 创建 XLWorkbook 对象,打开 Excel 文件
        using (var workbook = new XLWorkbook(filePath))
        {
            // 获取指定名称的工作表
            var worksheet = workbook.Worksheet(sheetName);

            // 获取工作表中使用的范围
            IXLRange usedRange = worksheet.RangeUsed();

            if (!string.IsNullOrEmpty(type))
            {
                if (type == "Row")
                {
                    var row = worksheet.Row(num);
                    usedRange = worksheet.Range(row.FirstCell(), row.LastCell());
                }
                else if (type == "Column")
                {
                    string columnName = GetExcelColumnName(num);
                    var column = worksheet.Column(columnName);
                    usedRange = worksheet.Range(column.FirstCell(), column.LastCell());
                }
            }

            // 读取每个单元格的值,并添加到 dataList 中
            foreach (var cell in usedRange.Cells())
            {
                dataList.Add(cell.Value.ToString());
            }
        }

        return dataList;
    }

    // 辅助方法:将列索引转换为 Excel 列名
    static string GetExcelColumnName(int columnNumber)
    {
        int dividend = columnNumber;
        string columnName = string.Empty;

        while (dividend > 0)
        {
            int modulo = (dividend - 1) % 26;
            columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
            dividend = (dividend - modulo) / 26;
        }

        return columnName;
    }
}

你可能感兴趣的:(C#基础,c#,excel,开发语言)