C#读取Excel表格的数据

时间:2023-03-09 19:47:37
C#读取Excel表格的数据

1、创建工程后,需要下载 EPPlus.dll 添加到工程中,这里有一个下载地址:https://download.csdn.net/download/myunity/10784634

2、下面仅实现读取Excel表格的列数据:

 using System;
using System.Collections.Generic;
using System.IO;
using OfficeOpenXml; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> list = GetExcelColumnValue(@"D:\UniuAndroid5.6.2\plan\配置表\excel\t_equip.xlsx", , ); for (int i = ; i < list.Count; ++i)
{
Console.WriteLine(list[i]);
} Console.ReadKey();
} /// <summary>
/// 读取Excel表格列数据
/// </summary>
/// <param name="path">Excel表格所在的路径</param>
/// <param name="sheetIndex">需要读取的Sheet页码序号</param>
/// <param name="columnIndex">需要读取的列序号</param>
/// <returns></returns>
static List<string> GetExcelColumnValue(string path, int sheetIndex, int columnIndex)
{
List<string> list = new List<string>(); FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
ExcelPackage excel = new ExcelPackage(fileStream);
ExcelWorksheet sheet = excel.Workbook.Worksheets[sheetIndex]; try
{
for (int i = ; i <= sheet.Dimension.End.Row; i++)
{
var cell = sheet.Cells[i, columnIndex];
if (cell != null && cell.Value != null)
list.Add(cell.Value.ToString());
}
}
catch
{
throw;
}
finally
{
sheet.Dispose();
excel.Dispose();
fileStream.Dispose();
} return list;
}
}
}

读取结果部分截图:

C#读取Excel表格的数据