C# - 按行、按列读取Excel文件中的数据
依赖库
右键单击项目,选择“管理NuGet程序包”。
搜索“EEPlus”并安装。
源代码
using OfficeOpenXml;
using System.Collections.Generic;
using System.IO;
namespace Utils
{
/// <summary>
/// Excel操作
/// </summary>
public class ExcelUtils
{
/// <summary>
/// 按行获取工作表中的所有数据
/// </summary>
/// <param name="sheet">工作表</param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 按列获取工作表中的所有数据
/// </summary>
/// <param name="sheet">工作表对象</param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 从文件中获取工作表
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="sheetIndex">工作表索引</param>
/// <returns></returns>
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;
}
}
}