一、简述
本文讲C#通过第三方库读取Excel的最简单的方法,下文给一个读取行数的例子。
二、依赖
引入nuget.org包如下:
<?xml version="1.0" encoding="utf-8"?> <packages> <package id="ExcelDataReader" version="3.4.2" targetFramework="net45" /> </packages>
二、打开xlsx文件并读取行数
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExcelLineReader { class Program { static void Main(string[] args) { Console.WriteLine("Please Input Folder Path:"); var folder = Console.ReadLine(); var excels = Directory.GetFiles(folder, "*.xlsx", SearchOption.AllDirectories); long totalRow = 0; foreach (var xlsx in excels) { using (Stream stream = File.OpenRead(xlsx)) { var reader = ExcelDataReader.ExcelReaderFactory.CreateOpenXmlReader(stream); var rowCount = reader.RowCount - 1; Console.WriteLine($"File:{xlsx} Count:{rowCount}"); totalRow += rowCount; reader.Close(); } } Console.WriteLine("All files Count:" + excels.Length + " All Lines:" + totalRow); Console.WriteLine("Press Enter to Exit."); Console.ReadKey(); } } }