using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Bailun.DC.Web.Base
{
    public class NpolHelper
    {
        #region ExcelToDataTable 将excel导入到datatable 

        /// <summary>
        /// 将excel导入到datatable 
        /// </summary>
        /// <param name="fs">excel数据流</param>
        /// <param name="fileName">excel名称，主要是取后面的后缀判断EXCEL03或者07版本</param>
        /// <param name="isColumnName">第一行是否是列名</param>
        /// <param name="SheetName">获取某一个工作簿的内容，如果为空的话，则获取所有；如果有多个的话，那么用,分隔</param>
        /// <param name="emptySheet">是否要获取为空的工作簿的内容</param>
        /// <returns>返回dicDataTable</returns>
        public static Dictionary<string, DataTable> ExcelToDataTable(Stream fs, string fileName, bool isColumnName, List<string> SheetName = null, bool emptySheet = true)
        {
            Dictionary<string, DataTable> dicDataTable = new Dictionary<string, DataTable>();
            DataColumn column = null;
            DataRow dataRow = null;
            IWorkbook workbook = null;
            ISheet sheet = null;
            IRow row = null;
            ICell cell = null;
            int startRow = 0;
            using (fs)
            {
                ExcelToDataTable(fs, fileName, isColumnName, ref dicDataTable, ref column, ref dataRow, ref workbook, ref sheet, ref row, ref cell, ref startRow, SheetName, emptySheet);
            }
            return dicDataTable;
        }

        /// <summary>  
        /// 将excel导入到datatable  
        /// </summary>  
        /// <param name="filePath">excel路径</param>  
        /// <param name="isColumnName">第一行是否是列名</param>  
        /// <param name="SheetName">获取某一个工作簿的内容，如果为空的话，则获取所有；如果有多个的话，那么用,分隔</param>
        /// <param name="emptySheet">是否要获取为空的工作簿的内容</param>
        /// <returns>返回datatables</returns>  
        public static Dictionary<string, DataTable> ExcelToDataTable(string filePath, bool isColumnName, List<string> SheetName = null, bool emptySheet = true)
        {
            Dictionary<string, DataTable> dicDataTable = new Dictionary<string, DataTable>();
            FileStream fs = null;
            DataColumn column = null;
            DataRow dataRow = null;
            IWorkbook workbook = null;
            ISheet sheet = null;
            IRow row = null;
            ICell cell = null;
            int startRow = 0;

            using (fs = File.OpenRead(filePath))
            {
                ExcelToDataTable(fs, filePath, isColumnName, ref dicDataTable, ref column, ref dataRow, ref workbook, ref sheet, ref row, ref cell, ref startRow, SheetName, emptySheet);
            }
            return dicDataTable;
        }
        #endregion

        #region 【private】ExcelToDataTable
        private static void ExcelToDataTable(Stream fs, string fileName, bool isColumnName, ref Dictionary<string, DataTable> dicDataTable, ref DataColumn column, ref DataRow dataRow, ref IWorkbook workbook, ref ISheet sheet, ref IRow row, ref ICell cell, ref int startRow, List<string> SheetName, bool emptySheet)
        {
            try
            {
                // 2007版本  
                if (fileName.ToLower().IndexOf(".xlsx") > 0) workbook = new XSSFWorkbook(fs);
                // 2003版本  
                else if (fileName.ToLower().IndexOf(".xls") > 0) workbook = new HSSFWorkbook(fs);

                DataTable dataTable = null;
                if (workbook != null)
                {
                    for (int k = 0; k < workbook.NumberOfSheets; k++)
                    {
                        sheet = workbook.GetSheetAt(k);
                        dataTable = new DataTable();
                        if (sheet != null)
                        {
                            string sName = sheet.SheetName;
                            if (SheetName != null && SheetName.Count > 0 && !SheetName.Contains(sName)) { continue; }

                            int rowCount = sheet.LastRowNum;//总行数  
                            if (rowCount > 0)
                            {
                                IRow firstRow = sheet.GetRow(0);//第一行  
                                int cellCount = firstRow.LastCellNum;//列数  

                                //构建datatable的列  
                                if (isColumnName)
                                {
                                    startRow = 1;//如果第一行是列名，则从第二行开始读取  
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        cell = firstRow.GetCell(i);
                                        if (cell != null)
                                        {
                                            if (cell.StringCellValue != null)
                                            {
                                                column = new DataColumn(cell.StringCellValue);
                                                dataTable.Columns.Add(column);
                                            }
                                        }
                                        else
                                        {
                                            cellCount = i;
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        column = new DataColumn("column" + (i + 1));
                                        dataTable.Columns.Add(column);
                                    }
                                }

                                //填充行  
                                for (int i = startRow; i <= rowCount; ++i)
                                {
                                    row = sheet.GetRow(i);
                                    if (row == null) continue;

                                    if (row.FirstCellNum == -1) continue;

                                    try
                                    {
                                        dataRow = dataTable.NewRow();
                                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                                        {
                                            cell = row.GetCell(j);
                                            if (cell == null) { dataRow[j] = ""; }
                                            else
                                            {
                                                switch (cell.CellType)
                                                {
                                                    case CellType.Blank: dataRow[j] = ""; break;
                                                    case CellType.Numeric:
                                                        short format = cell.CellStyle.DataFormat;
                                                        if (format == 14 || format == 31 || format == 57 || format == 58 || HSSFDateUtil.IsCellDateFormatted(cell)) dataRow[j] = cell.DateCellValue.ToString("yyyy-MM-dd HH:mm:ss");
                                                        else dataRow[j] = cell.NumericCellValue;
                                                        break;
                                                    case CellType.String: dataRow[j] = cell.StringCellValue; break;
                                                }
                                            }
                                        }
                                        dataTable.Rows.Add(dataRow);
                                    }
                                    catch (Exception ex)
                                    {

                                        throw ex;
                                    }
                                }
                            }
                            if (!emptySheet && !SheetName.Contains(sName) && dataTable.Rows.Count == 0) { continue; }

                            dicDataTable.Add(sName, dataTable);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (fs != null)
                {
                    fs.Close();
                }

            }
        }
        #endregion
    }
}
