C#讀取Excel文件的簡單方法

1、簡述spa

  本文講C#經過第三方庫讀取Excel的最簡單的方法,下文給一個讀取行數的例子。excel

2、依賴code

  引入nuget.org包以下:xml

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="ExcelDataReader" version="3.4.2" targetFramework="net45" />
</packages>

 

2、打開xlsx文件並讀取行數blog

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();
        }
    }
}
相關文章
相關標籤/搜索