C# - 按行、按列读取Excel文件中的数据

C# - 按行、按列读取Excel文件中的数据

依赖库

右键单击项目,选择“管理NuGet程序包”。
C# - 按行、按列读取Excel文件中的数据_第1张图片

搜索“EEPlus”并安装。
C# - 按行、按列读取Excel文件中的数据_第2张图片

源代码

using OfficeOpenXml;
using System.Collections.Generic;
using System.IO;

namespace Utils
{
    /// 
    /// Excel操作
    /// 
    public class ExcelUtils
    {
        /// 
        /// 按行获取工作表中的所有数据
        /// 
        /// 工作表
        /// 
        public static List<List<object>> GetWorksheetRows(ExcelWorksheet sheet)
        {
            try
            {
                List<List<object>> result = new List<List<object>>();

                for (int i = 1; i <= sheet.Dimension.End.Row; i++)
                {
                    List<object> row = new List<object>();

                    for (int j = 1; j <= sheet.Dimension.End.Column; j++)
                    {
                        var cell = sheet.Cells[i, j];
                        row.Add(cell == null ? null : cell.Value);
                    }
                    result.Add(row);
                }
                return result;
            }
            catch
            {
                throw;
            }
        }

        /// 
        /// 按列获取工作表中的所有数据
        /// 
        /// 工作表对象
        /// 
        public static List<List<object>> GetWorksheetColumns(ExcelWorksheet sheet)
        {
            try
            {
                List<List<object>> result = new List<List<object>>();

                for (int i = 1; i <= sheet.Dimension.End.Column; i++)
                {
                    List<object> col = new List<object>();

                    for (int j = 1; j <= sheet.Dimension.End.Row; j++)
                    {
                        var cell = sheet.Cells[j, i];
                        col.Add(cell == null ? null : cell.Value);

                    }
                    result.Add(col);
                }

                return result;
            }
            catch
            {
                throw;
            }
        }

        /// 
        /// 从文件中获取工作表
        /// 
        /// 文件路径
        /// 工作表索引
        /// 
        public static ExcelWorksheet GetWorksheetFromFile(string path, int sheetIndex)
        {
            FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
            ExcelPackage excel = new ExcelPackage(fileStream);
            ExcelWorksheet sheet = excel.Workbook.Worksheets[sheetIndex];
            fileStream.Close();
            return sheet;
        }
    }
}

你可能感兴趣的:(c#)