本方法引用 Aspose.Cells.dll,ICSharpCode.SharpZipLib.dll ,NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,NPOI.OpenXmlFormats.dll

static void Main(string[] args)
        {
            string filepath = @"E:\我的.xlsx";

            IReadEntDataFromExcel iReadEntDataFromExcel = new  ReadEntDataFromExcelInfo();
            List<String> result=iReadEntDataFromExcel.ReadEntDataFromExcel(filepath);
        }

建一个类IReadEntDataFromExcel.cs:

public interface IReadEntDataFromExcel
    {
       List<string> ReadEntDataFromExcel(string filePath);
    }

建一个类NOPIExcelHelper.cs  :

 

public class NOPIExcelHelper
    {
        #region 单例定义
        private static object lockObject = new object();
        protected NOPIExcelHelper()
        {
        }

        private static volatile NOPIExcelHelper _instance;
        public static NOPIExcelHelper Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (lockObject)
                    {
                        return _instance ?? (_instance = new NOPIExcelHelper());
                    }
                }
                return _instance;
            }
        }

        #endregion 单例定义

        public static DataSet ExcelToDataSet(string excelPath)
        {
            DataSet dataSet = new DataSet();
            dataSet = ExcelToDataSet(excelPath, false);
            return dataSet;
        }

        public static DataSet ExcelToDataSet(string excelPath, bool firstRowAsHeader)
        {
            int sheetCount;
            return ExcelToDataSet(excelPath, firstRowAsHeader, out sheetCount);
        }

        public static DataSet ExcelToDataSet(string excelPath, bool firstRowAsHeader, out int sheetCount)
        {
            sheetCount = 0;
            using (DataSet ds = new DataSet())
            {
                using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
                {
                    if (Path.GetExtension(excelPath).ToLower() == ".xls".ToLower())
                    {
                        HSSFWorkbook workbook = new HSSFWorkbook(fileStream);
                        HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook);

                        sheetCount = workbook.NumberOfSheets;

                        for (int i = 0; i < sheetCount; ++i)
                        {
                            HSSFSheet sheet = workbook.GetSheetAt(i) as HSSFSheet;
                            DataTable dt = ExcelToDataTable(sheet, evaluator, firstRowAsHeader);
                            ds.Tables.Add(dt);
                        }
                    }
                    else if (Path.GetExtension(excelPath).ToLower() == ".xlsx".ToLower())
                    {
                        XSSFWorkbook workbook = new XSSFWorkbook(fileStream);
                        XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(workbook);

                        sheetCount = workbook.NumberOfSheets;

                        for (int i = 0; i < sheetCount; ++i)
                        {
                            XSSFSheet sheet = workbook.GetSheetAt(i) as XSSFSheet;
                            DataTable dt = ExcelToDataTableX(sheet, evaluator, firstRowAsHeader);
                            ds.Tables.Add(dt);
                        }

                    }

                }
                return ds;
            }
        }

        public static DataTable ExcelToDataTable(string excelPath, string sheetName)
        {
            return ExcelToDataTable(excelPath, sheetName, true);
        }

        public static DataTable ExcelToDataTable(string excelPath, string sheetName, bool firstRowAsHeader)
        {
            using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
            {
                HSSFWorkbook workbook = new HSSFWorkbook(fileStream);

                HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook);

                HSSFSheet sheet = workbook.GetSheet(sheetName) as HSSFSheet;

                return ExcelToDataTable(sheet, evaluator, firstRowAsHeader);
            }
        }

        private static DataTable ExcelToDataTable(HSSFSheet sheet, HSSFFormulaEvaluator evaluator, bool firstRowAsHeader)
        {
            if (firstRowAsHeader)
            {
                return ExcelToDataTableFirstRowAsHeader(sheet, evaluator);
            }
            else
            {
                return ExcelToDataTable(sheet, evaluator);
            }
        }

        private static DataTable ExcelToDataTableX(XSSFSheet sheet, XSSFFormulaEvaluator evaluator, bool firstRowAsHeader)
        {
            if (firstRowAsHeader)
            {
                return ExcelToDataTableFirstRowAsHeaderX(sheet, evaluator);
            }
            else
            {
                return ExcelToDataTableX(sheet, evaluator);
            }
        }
        private static DataTable ExcelToDataTableFirstRowAsHeader(HSSFSheet sheet, HSSFFormulaEvaluator evaluator)
        {
            using (DataTable dt = new DataTable())
            {
                HSSFRow firstRow = sheet.GetRow(0) as HSSFRow;
                int cellCount = GetCellCount(sheet);

                for (int i = 0; i < cellCount; i++)
                {
                    if (firstRow.GetCell(i) != null)
                    {
                        dt.Columns.Add(firstRow.GetCell(i).ToString() ?? string.Format("F{0}", i + 1), typeof(string));
                    }
                    else
                    {
                        dt.Columns.Add(string.Format("F{0}", i + 1), typeof(string));
                    }
                }

                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    HSSFRow row = sheet.GetRow(i) as HSSFRow;
                    DataRow dr = dt.NewRow();
                    FillDataRowByHSSFRow(row, evaluator, ref dr);
                    dt.Rows.Add(dr);
                }

                dt.TableName = sheet.SheetName;
                return dt;
            }
        }


        private static DataTable ExcelToDataTableFirstRowAsHeaderX(XSSFSheet sheet, XSSFFormulaEvaluator evaluator)
        {
            using (DataTable dt = new DataTable())
            {
                XSSFRow firstRow = sheet.GetRow(0) as XSSFRow;
                int cellCount = GetCellCountX(sheet);

                for (int i = 0; i < cellCount; i++)
                {
                    if (firstRow.GetCell(i) != null)
                    {
                        dt.Columns.Add(firstRow.GetCell(i).ToString() ?? string.Format("F{0}", i + 1), typeof(string));
                    }
                    else
                    {
                        dt.Columns.Add(string.Format("F{0}", i + 1), typeof(string));
                    }
                }

                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    XSSFRow row = sheet.GetRow(i) as XSSFRow;
                    DataRow dr = dt.NewRow();
                    FillDataRowByHSSFRowX(row, evaluator, ref dr);
                    dt.Rows.Add(dr);
                }

                dt.TableName = sheet.SheetName;
                return dt;
            }
        }
        private static DataTable ExcelToDataTable(HSSFSheet sheet, HSSFFormulaEvaluator evaluator)
        {
            using (DataTable dt = new DataTable())
            {
                if (sheet.LastRowNum != 0)
                {
                    int cellCount = GetCellCount(sheet);

                    for (int i = 0; i < cellCount; i++)
                    {
                        dt.Columns.Add(string.Format("F{0}", i), typeof(string));
                    }

                    for (int i = 0; i < sheet.FirstRowNum; ++i)
                    {
                        DataRow dr = dt.NewRow();
                        dt.Rows.Add(dr);
                    }

                    for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
                    {
                        HSSFRow row = sheet.GetRow(i) as HSSFRow;
                        DataRow dr = dt.NewRow();
                        FillDataRowByHSSFRow(row, evaluator, ref dr);
                        dt.Rows.Add(dr);
                    }
                }

                dt.TableName = sheet.SheetName;
                return dt;
            }
        }

        private static DataTable ExcelToDataTableX(XSSFSheet sheet, XSSFFormulaEvaluator evaluator)
        {
            using (DataTable dt = new DataTable())
            {
                if (sheet.LastRowNum != 0)
                {
                    int cellCount = GetCellCountX(sheet);

                    for (int i = 0; i < cellCount; i++)
                    {
                        dt.Columns.Add(string.Format("F{0}", i), typeof(string));
                    }

                    for (int i = 0; i < sheet.FirstRowNum; ++i)
                    {
                        DataRow dr = dt.NewRow();
                        dt.Rows.Add(dr);
                    }

                    for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
                    {
                        XSSFRow row = sheet.GetRow(i) as XSSFRow;
                        DataRow dr = dt.NewRow();
                        FillDataRowByHSSFRowX(row, evaluator, ref dr);
                        dt.Rows.Add(dr);
                    }
                }

                dt.TableName = sheet.SheetName;
                return dt;
            }
        }

        private static void FillDataRowByHSSFRow(HSSFRow row, HSSFFormulaEvaluator evaluator, ref DataRow dr)
        {
            if (row != null)
            {
                for (int j = 0; j < dr.Table.Columns.Count; j++)
                {
                    HSSFCell cell = row.GetCell(j) as HSSFCell;

                    if (cell != null)
                    {
                        switch (cell.CellType)
                        {
                            case CellType.Blank:
                                dr[j] = DBNull.Value;
                                break;
                            case CellType.Boolean:
                                dr[j] = cell.BooleanCellValue;
                                break;
                            case CellType.Numeric:
                                if (DateUtil.IsCellDateFormatted(cell))
                                {
                                    dr[j] = cell.DateCellValue;
                                }
                                else
                                {
                                    dr[j] = cell.NumericCellValue;
                                }
                                break;
                            case CellType.String:
                                dr[j] = cell.StringCellValue;
                                break;
                            case CellType.Error:
                                dr[j] = cell.ErrorCellValue;
                                break;
                            case CellType.Formula:
                                cell = evaluator.EvaluateInCell(cell) as HSSFCell;
                                dr[j] = cell.ToString();
                                break;
                            default:
                                throw new NotSupportedException(string.Format("Catched unhandle CellType[{0}]", cell.CellType));
                        }
                    }
                }
            }
        }
        private static void FillDataRowByHSSFRowX(XSSFRow row, XSSFFormulaEvaluator evaluator, ref DataRow dr)
        {
            if (row != null)
            {
                for (int j = 0; j < dr.Table.Columns.Count; j++)
                {
                    XSSFCell cell = row.GetCell(j) as XSSFCell;

                    if (cell != null)
                    {
                        switch (cell.CellType)
                        {
                            case CellType.Blank:
                                dr[j] = DBNull.Value;
                                break;
                            case CellType.Boolean:
                                dr[j] = cell.BooleanCellValue;
                                break;
                            case CellType.Numeric:
                                if (DateUtil.IsCellDateFormatted(cell))
                                {
                                    dr[j] = cell.DateCellValue;
                                }
                                else
                                {
                                    dr[j] = cell.NumericCellValue;
                                }
                                break;
                            case CellType.String:
                                dr[j] = cell.StringCellValue;
                                break;
                            case CellType.Error:
                                dr[j] = cell.ErrorCellValue;
                                break;
                            case CellType.Formula:
                                cell = evaluator.EvaluateInCell(cell) as XSSFCell;
                                dr[j] = cell.ToString();
                                break;
                            default:
                                throw new NotSupportedException(string.Format("Catched unhandle CellType[{0}]", cell.CellType));
                        }
                    }
                }
            }
        }

        private static int GetCellCount(HSSFSheet sheet)
        {
            int firstRowNum = sheet.FirstRowNum;

            int cellCount = 0;

            for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; ++i)
            {
                HSSFRow row = sheet.GetRow(i) as HSSFRow;

                if (row != null && row.LastCellNum > cellCount)
                {
                    cellCount = row.LastCellNum;
                }
            }

            return cellCount;
        }

        private static int GetCellCountX(XSSFSheet sheet)
        {
            int firstRowNum = sheet.FirstRowNum;

            int cellCount = 0;

            for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; ++i)
            {
                XSSFRow row = sheet.GetRow(i) as XSSFRow;

                if (row != null && row.LastCellNum > cellCount)
                {
                    cellCount = row.LastCellNum;
                }
            }

            return cellCount;
        }
    }

建一个类ReadEntDataFromExcel.cs :

 

public class ReadEntDataFromExcelInfo : IReadEntDataFromExcel
    {
        #region 单例定义
        private static object lockObject = new object();
        public ReadEntDataFromExcelInfo()
        {
        }

        private static volatile ReadEntDataFromExcelInfo _instance;
        public static ReadEntDataFromExcelInfo Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (lockObject)
                    {
                        return _instance ?? (_instance = new ReadEntDataFromExcelInfo());
                    }
                }
                return _instance;
            }
        }

        #endregion 单例定义

        //protected IWriteLogMess WriteLogMessProvider
        //{
        //    get
        //    {
        //        return WriteLogMess.Instance;
        //    }
        //}

        public List<string> ReadEntDataFromExcel(string filePath)
        {
            //string filePath = @"E:\Table\企业征信存量数据名单表0630.xlsx";
            List<string> result = null;
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException("ReadEntDataFromExcel 参数为空");
            }
            try
            {
                result = this.ReadEntDataFromExcelProvider(filePath);
            }
            catch (Exception ex)
            {
                //this.WriteLogMessProvider.WritreLogExption(ex, "ReadEntDataFromExcelInfo/ReadEntDataFromExcel");
            }

            return result;
        }

        private List<string> ReadEntDataFromExcelProvider(string filePath)
        {
            NOPIExcelHelper NPOIHandler = NOPIExcelHelper.Instance;
            DataSet dataSet = new DataSet();
            dataSet = NOPIExcelHelper.ExcelToDataSet(filePath);
            DataTable table = new DataTable();

            foreach (DataTable datatable in dataSet.Tables)
            {
                table.Merge(datatable);
            }

            var hashset = new HashSet<string>();
            foreach (DataRow dr in table.Rows)
            {
                hashset.Add(dr["F1"].ToString().Trim());
            }

            List<String> result = hashset.ToList();
            return result;
        }
        //public static IList<T> ConvertTo<T>(DataTable table)
        //{
        //    if (table == null)
        //    {
        //        return null;
        //    }

        //    IList<DataRow> rows = new List<DataRow>();

        //    foreach (DataRow row in table.Rows)
        //    {
        //        rows.Add(row);
        //    }

        //    return ConvertTo<T>(rows);
        //}  

    }

 

posted on 2016-11-21 17:26  菜鸟Only  阅读(913)  评论(0编辑  收藏  举报