C#读取Excel文件的简单方法
C#读取Excel文件的简单方法
一、简述
本文讲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();
}
}
}
C#读取Excel文件的简单方法
https://www.dearcloud.cn/2019/01/07/20200310-cnblogs-old-posts/20190107-CSharp读取Excel文件的简单方法/