上篇文章向大家介绍了用DocumentFormat.OpenXml.dll读取excel的方法,这里再向大家介绍一种轻量级简便的方法,用的是Excel.dll,及ICSharpCode.SharpZipLib.dll, 很简单,只需要在vs2013中通过add reference->Manage NuGet Packages->找到ExcelDataReader->点击Install。
Code:
public class ExcelDataReader { private string path; public string Path { get { return path; } set { path = value; } } private bool isFirstRowAsColumnNames; public bool IsFirstRowAsColumnNames { get { return IsFirstRowAsColumnNames; } set { isFirstRowAsColumnNames = value; } } public ExcelDataReader(string path, bool isFirstRowAsColumnNames) { this.path = path; this.isFirstRowAsColumnNames = isFirstRowAsColumnNames; } private IExcelDataReader GetExcelDataReader() { using (FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.Read)) { IExcelDataReader dataReader; if (path.EndsWith(".xls")) { dataReader = ExcelReaderFactory.CreateBinaryReader(fileStream); } else if (path.EndsWith(".xlsx")) { dataReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream); } else { throw new Exception("The file to be process is not an excel file."); } dataReader.IsFirstRowAsColumnNames = isFirstRowAsColumnNames; return dataReader; } } private DataSet GetExcelDataAsDataSet() { return GetExcelDataReader().AsDataSet(); } private DataTable GetExcelWorkSheet(string workSheetName) { DataSet dataSet = GetExcelDataAsDataSet(); var sheets = from DataTable sheet in dataSet.Tables select sheet.TableName; DataTable workSheet = dataSet.Tables[workSheetName]; if (workSheet == null) { throw new Exception(string.Format("The worksheet {0} does not exist, has an incorrect name, or does not have any data in the worksheet", workSheetName)); } return workSheet; } private IEnumerable<string> GetWorkSheetNames() { DataSet dataSet = GetExcelDataAsDataSet(); var sheets = from DataTable sheet in dataSet.Tables select sheet.TableName; return sheets; } public List<List<DataRow>> GetData() { List<List<DataRow>> dataRows = new List<List<DataRow>>(); IEnumerable<string> workSheets = GetWorkSheetNames(); logger.Debug("Worksheets count :{0}.", workSheets.Count()); foreach (string sheet in workSheets) { try { DataTable workSheet = GetExcelWorkSheet(sheet); List<DataRow> rows = (from DataRow row in workSheet.Rows where !string.IsNullOrEmpty(row[0].ToString()) select row).ToList(); if (rows.Count > 0) { dataRows.Add(rows); } } catch (Exception ex) { } } return dataRows; } } }