npoi操作excel 讀取 插入 寫入等

    public class NPOIExcel
    {
        public const string pattern = @"^\d+(\.\d+)?$";//判斷是否是數字
        public static void CreateFile(string filePath, string sheetName)
        {
            if (!File.Exists(filePath))
            {
                //文件不存在 創建新文件寫入
                if (filePath.Contains(".xlsx") || filePath.Contains(".ett") || filePath.Contains(".xlsm"))
                {
                    XSSFWorkbook workbook = new XSSFWorkbook();
                    workbook.CreateSheet(sheetName);
                    FileStream fs = new FileStream(filePath, FileMode.Create);
                    workbook.Write(fs);
                    fs.Close();
                }
                else if (filePath.Contains(".xls") || filePath.Contains(".et"))
                {
                    HSSFWorkbook workbook = new HSSFWorkbook();
                    workbook.CreateSheet(sheetName);
                    FileStream fs = new FileStream(filePath, FileMode.Create);
                    workbook.Write(fs);
                    fs.Close();
                }
            }
        }

        /// <summary>
        /// 把DataTable的數據寫入到指定的excel文件中
        /// </summary>
        /// <param name="TargetFileNamePath">目標文件excel的路徑</param>
        /// <param name="sourceData">要寫入的數據</param>
        /// <param name="sheetName">excel表中的sheet的名稱,可以根據情況自己起</param>
        /// <param name="IsWriteColumnName">是否寫入DataTable的列名稱</param>
        /// <returns>返回寫入的行數</returns>
        public static int DataTableToExcel(string TargetFileNamePath, System.Data.DataTable sourceData, string TemplateSheetName, string sheetName, bool IsWriteColumnName, bool Overwrite, string startCell, Dictionary<string, object> ConvertColumnTypes = null)
        {
            bool status = false;
            //數據驗證
            if (!File.Exists(TargetFileNamePath))
            {
                //excel文件的路徑不存在
                throw new ArgumentException(ConfigStringHelper.ExcelError_NotArgumentExceptionFilePath);
            }
            FileStream fs = new FileStream(TargetFileNamePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//讀取流

            ////根據Excel文件的後綴名創建對應的workbook
            IWorkbook workbook = null;
            if (TargetFileNamePath.IndexOf(".xlsx") > 0 || TargetFileNamePath.IndexOf(".ett") > 0 || TargetFileNamePath.IndexOf(".xlsm") > 0)
            {  //2007版本的excel
                workbook = new XSSFWorkbook(fs);
            }
            else if (TargetFileNamePath.IndexOf(".xls") > 0 || TargetFileNamePath.IndexOf(".et") > 0) //2003版本的excel
            {
                workbook = new HSSFWorkbook(fs);
            }
            else
            {
                return -1;    //都不匹配或者傳入的文件根本就不是excel文件,直接返回
            }
            ISheet sheet = workbook.GetSheetAt(0);//獲取工作表
            int SheetCount = workbook.NumberOfSheets;//獲取表的數量
            string[] SheetName = new string[SheetCount];//保存表的名稱
            //excel表的sheet名
            //ISheet sheet = null;
            if (!string.IsNullOrEmpty(TemplateSheetName))
            {
                int idex = workbook.GetSheetIndex(TemplateSheetName);
                if (string.IsNullOrEmpty(sheetName))
                {
                    throw new ArgumentException(ConfigStringHelper.ExcelError_NotSheetTemplate);
                }
                //修改sheet名字
                workbook.SetSheetName(idex, sheetName);
            }
            for (int i = 0; i < SheetCount; i++)
            {
                SheetName[i] = workbook.GetSheetName(i).ToLower();
                //獲取sheet的索引

            }
            if (SheetName.Contains(sheetName.ToLower()) && Overwrite == false)
            {
                sheet = workbook.GetSheet(sheetName);
                status = false;
            }
            else if (SheetName.Contains(sheetName.ToLower()) && Overwrite == true)
            {
                workbook.RemoveSheetAt(workbook.GetSheetIndex(sheetName));
                sheet = workbook.CreateSheet(sheetName);
                status = true;
            }
            if (!SheetName.Contains(sheetName.ToLower()))
            {
                sheet = workbook.CreateSheet(sheetName);
            }
            if (sheet == null) return -1;   //無法創建sheet,則直接返回
            //寫入Excel的行數
            int WriteRowCount = 0;

            int colunmIndex = 0;

            if (!string.IsNullOrEmpty(startCell))
            {
                CellRangeAddress cellRangeAddress = CellRangeAddress.ValueOf(startCell);
                WriteRowCount = cellRangeAddress.FirstRow;
                colunmIndex = cellRangeAddress.FirstColumn;

            }
            //這裏獲取源數據的總行和列
            var SourceRows = sourceData.Rows.Count;//
            var SourceColumns = sourceData.Columns.Count;//
            if (IsWriteColumnName == false)
            {
                IRow ColumnNameRow = null;
                //sheet表創建新的一行,即第一行
                if (status == true && string.IsNullOrEmpty(startCell))
                {
                    //表示覆蓋
                    ColumnNameRow = sheet.CreateRow(0);
                }
                else if (status == false && string.IsNullOrEmpty(startCell))
                {
                    //表示不覆蓋,此處需要判斷範圍內是否存在數據
                    for (var i = WriteRowCount; i < SourceRows + WriteRowCount; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null)
                        {
                            row = sheet.CreateRow(i);
                        }
                        for (var j = colunmIndex; j < SourceColumns + colunmIndex; j++)
                        {
                            ICell cell = row.GetCell(j);
                            if (cell == null)
                            {
                                cell = row.CreateCell(j);
                            }
                            else
                            {
                                throw new ArgumentException(ConfigStringHelper.ExcelError_WriteFailure);
                            }
                        }
                    }
                    ColumnNameRow = sheet.CreateRow(0);
                }
                if (!string.IsNullOrEmpty(startCell) && status == false)
                {
                    //表示不覆蓋,從指定的位置處寫入,需要判斷指定位置是否有數據
                    for (var i = WriteRowCount; i < SourceRows + WriteRowCount; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null)
                        {
                            row = sheet.CreateRow(i);
                        }
                        for (var j = colunmIndex; j < SourceColumns + colunmIndex; j++)
                        {
                            ICell cell = row.GetCell(j);
                            if (cell == null)
                            {
                                cell = row.CreateCell(j);
                            }
                            else
                            {
                                throw new ArgumentException(ConfigStringHelper.ExcelError_WriteFailure);
                            }
                            var firsLine = row.GetCell(j).ToString();
                        }
                    }
                    ColumnNameRow = sheet.CreateRow(WriteRowCount);
                }
                else if (!string.IsNullOrEmpty(startCell) && status == true)
                {
                    //表示覆蓋,從指定的位置處寫入
                    ColumnNameRow = sheet.CreateRow(WriteRowCount);
                }
                //IRow ColumnNameRow = sheet.CreateRow(0); //0下標代表第一行
                int ColumnCount = colunmIndex;//開始列
                //進行寫入DataTable的列名
                for (int colunmNameIndex = 0; colunmNameIndex < sourceData.Columns.Count; colunmNameIndex++)
                {

                    ColumnNameRow.CreateCell(ColumnCount).SetCellValue(sourceData.Columns[colunmNameIndex].ColumnName);
                    ColumnCount++;
                }
                WriteRowCount++;
            }
            bool endStatus = false;
            int count = 0;
            count = (WriteRowCount) + (sheet.LastRowNum);
            //寫入數據
            for (int row = 0; row < sourceData.Rows.Count; row++)
            {
                IRow newRow = null;
                //sheet表創建新的一行
                if (status == false && string.IsNullOrEmpty(startCell))
                {
                    if (endStatus == false)
                    {
                        if (IsWriteColumnName == false)
                        {
                        }
                        else
                        {
                            for (var i = WriteRowCount + 1; i < SourceRows + WriteRowCount + 1; i++)
                            {
                                IRow row_a = sheet.GetRow(i);
                                if (row_a == null)
                                {
                                    row_a = sheet.CreateRow(i);
                                }
                                for (var j = colunmIndex; j < SourceColumns + colunmIndex; j++)
                                {
                                    ICell cell = row_a.GetCell(j);
                                    if (cell == null)
                                    {
                                        cell = row_a.CreateCell(j);
                                    }
                                    else
                                    {
                                        throw new ArgumentException(ConfigStringHelper.ExcelError_WriteFailure);
                                    }
                                    var firsLine = row_a.GetCell(j).ToString();
                                }
                            }
                        }
                    }
                    newRow = sheet.CreateRow(WriteRowCount);
                }
                else if (status == true && string.IsNullOrEmpty(startCell))
                {
                    //表示覆蓋
                    newRow = sheet.CreateRow(WriteRowCount);
                }
                if (!string.IsNullOrEmpty(startCell) && status == true)
                {
                    //表示覆蓋,從指定的位置處寫入
                    newRow = sheet.CreateRow(WriteRowCount);
                }
                else if (!string.IsNullOrEmpty(startCell) && status == false)
                {

                    if (endStatus == false)
                    {
                        //表示不覆蓋,從指定的位置處寫入,需要判斷指定位置是否有數據
                        if (IsWriteColumnName == false)
                        {
                        }
                        else
                        {
                            for (var i = WriteRowCount + 1; i < SourceRows + WriteRowCount + 1; i++)
                            {
                                IRow row_a = sheet.GetRow(i);
                                if (row_a == null)
                                {
                                    row_a = sheet.CreateRow(i);
                                }
                                for (var j = colunmIndex; j < SourceColumns + colunmIndex; j++)
                                {
                                    ICell cell = row_a.GetCell(j);
                                    if (cell == null)
                                    {
                                        cell = row_a.CreateCell(j);
                                    }
                                    else
                                    {
                                        throw new ArgumentException(ConfigStringHelper.ExcelError_WriteFailure);
                                    }
                                    var firsLine = row_a.GetCell(j).ToString();
                                }
                            }
                        }

                    }
                    newRow = sheet.CreateRow(WriteRowCount);
                }
                int Count = colunmIndex;//開始列
                for (int column = 0; column < sourceData.Columns.Count; column++)
                {
                    string columnName = sourceData.Columns[Convert.ToInt32(column)].ColumnName;
                    string text = sourceData.Rows[row][column].ToString();
                    Type type = sourceData.Columns[columnName].DataType;
                    if (!string.IsNullOrEmpty(text))
                    {
                        if (type.Name.Contains("Int32") || type.Name.Contains("Int16") || type.Name.Contains("Int64") || type.Name.Contains("SByte") || type.Name.Contains("Single") || type.Name.Contains("Double") || type.Name.Contains("Decimal"))
                        {
                            newRow.CreateCell(Count).SetCellValue(Convert.ToDouble(text));
                        }
                        else if (type.Name == "Boolean")
                        {
                            newRow.CreateCell(Count).SetCellValue(Convert.ToBoolean(text));
                        }
                        else if (type.Name == "DateTime")
                        {
                            newRow.CreateCell(Count).SetCellValue(Convert.ToDateTime(text));
                        }
                        else if (type.Name == "String")
                        {
                            if (ConvertColumnTypes != null)
                            {
                                if (ConvertColumnTypes.ContainsKey(columnName))
                                {
                                    double d;
                                    bool b = double.TryParse(text, out d);
                                    if (b)
                                    {
                                        newRow.CreateCell(Count).SetCellValue(d);
                                    }
                                    else
                                    {
                                        newRow.CreateCell(Count).SetCellValue(text);
                                    }
                                }
                                else
                                {
                                    newRow.CreateCell(Count).SetCellValue(text);
                                }
                            }
                            else
                            {
                                newRow.CreateCell(Count).SetCellValue(text);
                            }
                        }
                    }
                    else
                    {
                        if (ConvertColumnTypes != null)
                        {
                            if (ConvertColumnTypes.ContainsKey(columnName))
                            {
                                if (ConvertColumnTypes[columnName] != null)
                                {
                                    newRow.CreateCell(Count).SetCellValue(Convert.ToDouble(ConvertColumnTypes[columnName]));
                                }
                            }
                        }
                    }
                    Count++;
                }
                WriteRowCount++;
                endStatus = true;
            }
            //寫入到excel中
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                using (FileStream fs1 = new FileStream(TargetFileNamePath, FileMode.Create, FileAccess.Write))
                {
                    byte[] _data = ms.ToArray();
                    fs1.Write(_data, 0, _data.Length);
                    fs1.Flush();
                    _data = null;
                }
            }
            return WriteRowCount;
        }

        /// <summary>
        /// 獲取excel中的Sheet
        /// </summary>
        public static List<string> GetMultipleSheets(string fileName)
        {
            List<string> list = new List<string>();
            Dictionary<int, string> t = new Dictionary<int, string>();
            ISheet sheet = null;
            IWorkbook workbook = null;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook(fs);
                else if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(fs);
                int count = workbook.NumberOfSheets; //獲取所有SheetName
                for (int i = 0; i < count; i++)
                {
                    sheet = workbook.GetSheetAt(i);
                    if (sheet.LastRowNum > 0)
                    {
                        t.Add(i, workbook.GetSheetAt(i).SheetName);
                        list.Add(workbook.GetSheetAt(i).SheetName);
                    }

                }
                return list;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (fs != null)
                    fs.Dispose();
            }
        }

        /// <summary>
        /// Excel讀取Sheets
        /// </summary>
        /// <param name="file">導入路徑</param>
        /// <returns></returns>
        public static List<string> GetSheetNames(string file)
        {
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook;
                if (fileExt == ".xlsx" || fileExt == ".ett" || fileExt == ".xlsm")
                {
                    workbook = new XSSFWorkbook(fs);
                }
                else if (fileExt == ".xls" || fileExt == ".et")
                {
                    workbook = new HSSFWorkbook(fs);
                }
                else
                {
                    workbook = null;
                }
                if (workbook == null)
                {
                    return null;
                }
                int sheetCount = workbook.NumberOfSheets;//獲取表的數量
                List<string> sheetNames = new List<string>();//保存表的名稱
                for (int i = 0; i < sheetCount; i++)
                {
                    sheetNames.Add(workbook.GetSheetName(i));
                }
                return sheetNames;
            }
        }
        /*
        /// <summary>
        /// Excel讀取Sheets
        /// </summary>
        /// <param name="file">導入路徑</param>
        /// <returns></returns>
        public static List<string> GetSheetNames(IWorkbook workbook)
        {
            int sheetCount = workbook.NumberOfSheets;//獲取表的數量
            List<string> sheetNames = new List<string>();//保存表的名稱
            for (int i = 0; i < sheetCount; i++)
            {
                sheetNames.Add(workbook.GetSheetName(i));
            }
            return sheetNames;
        }
        */
        /// <summary>
        /// Excel讀取Datable
        /// </summary>
        /// <param name="file">導入路徑</param>
        /// <returns></returns>
        public static DataTable ExcelToTable(string file, bool isFirstRowColumn, string sheetName = "")
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            ISheet sheet = null;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                if (fileExt == ".xlsx" || fileExt == ".ett" || fileExt == ".xlsm")
                {
                    workbook = new XSSFWorkbook(fs);
                }
                else if (fileExt == ".xls" || fileExt == ".et")
                {
                    workbook = new HSSFWorkbook(fs);
                }
                else
                {
                    workbook = null;
                }
                if (workbook == null)
                {
                    return null;
                }
                sheet = workbook.GetSheetAt(0);
                if (!string.IsNullOrEmpty(sheetName))
                {
                    int SheetCount = workbook.NumberOfSheets;//獲取表的數量
                    string[] SheetName = new string[SheetCount];//保存表的名稱
                    for (int i = 0; i < SheetCount; i++)
                    {
                        SheetName[i] = workbook.GetSheetName(i).ToLower();

                    }
                    if (SheetName.Contains(sheetName.ToLower()))
                    {
                        sheet = workbook.GetSheet(sheetName);
                    }
                    else
                    {
                        throw new ArgumentException(ConfigStringHelper.ExcelError_NotSheet);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }
                var rowCount = sheet.LastRowNum + 1;//得到總行數
                //z這裏遍歷得到最大列數,因爲存在第一行殘缺爲空的情況
                List<int> array = new List<int>();
                for (var i = 0; i < rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row == null)
                    {
                        row = sheet.CreateRow(i);
                    }
                    //array.Add(row.Cells.Count);//獲取有效列
                    array.Add(row.LastCellNum);//獲取所有列(包含空列以及殘缺)
                }
                var maxValue = array.Max();//得到最大列數
                int Index = 0;//用來判斷是否使用列頭
                List<int> columns = new List<int>();
                //創建列頭
                if (isFirstRowColumn == false)
                {
                    //第一行不作爲DataTable的列名
                    Index = sheet.FirstRowNum;
                    for (int i = 0; i < maxValue; i++)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                        columns.Add(i);
                    }
                }
                else
                {
                    //判斷第一行是否是合併單元格
                    IRow row = sheet.GetRow(0);
                    for (int i = 0; i < row.Cells.Count; i++)
                    {
                        ICell cell = row.GetCell(i);
                        if (cell == null)
                        {
                            cell = row.CreateCell(i);
                        }
                        var cellfirst = cell.IsMergedCell;
                        if (cellfirst == true)
                        {
                            //說明第一行有合併單元格無法作爲列,此時需要提醒用戶
                            throw new Exception(ConfigStringHelper.ExcelError_IncludeHeaders);
                        }
                    }
                    Index = sheet.FirstRowNum + 1;
                    //第一行作爲DataTable列名
                    //表頭  
                    IRow header = sheet.GetRow(sheet.FirstRowNum);
                    if (header == null)
                    {
                        for (int i = 0; i < maxValue; i++)
                        {
                            dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                            columns.Add(i);
                        }
                    }
                    else
                    {
                        //這裏用來檢測第一行數據是否合法,可以用來做列頭
                        List<string> lst = new List<string>();
                        for (int i = 0; i < header.LastCellNum; i++)
                        {
                            object obj = GetValueType(header.GetCell(i));
                            if (obj == null)
                            {
                                lst.Add("Columns" + i.ToString());
                            }
                            else
                            {
                                lst.Add(obj.ToString());
                            }

                        }
                        bool status = lst.GroupBy(n => n).Any(c => c.Count() > 1);
                        if (status == true)
                        {
                            //說明第一行存在重複數據無法作爲列頭
                            throw new Exception(ConfigStringHelper.ExcelError_IncludeHeadersData);
                        }
                        for (int i = 0; i < maxValue; i++)
                        {
                            object obj = GetValueType(header.GetCell(i));
                            if (obj == null || obj.ToString() == string.Empty)
                            {
                                dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                            }
                            else
                                dt.Columns.Add(new DataColumn(obj.ToString()));
                            columns.Add(i);
                        }
                    }
                }
                //數據  
                for (int i = Index; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                    }
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }
        /// <summary>
        /// 獲取單元格類型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return null;
                case CellType.Boolean:
                    return cell.BooleanCellValue;
                case CellType.Numeric:
                    if (HSSFDateUtil.IsCellDateFormatted(cell))//日期類型
                    {
                        return Convert.ToDateTime(cell.DateCellValue);
                    }
                    else//其他數字類型
                    {
                        return Convert.ToDouble(cell.NumericCellValue);
                    }
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Error:
                  
                    XSSFCell xSSFCell = cell as XSSFCell;

                    if (null != xSSFCell)
                    {
                        return xSSFCell.ErrorCellString;
                    }
                    else
                    {
                        return cell.ToString();
                    }
                case CellType.Formula:
                    try
                    {
                        return cell.NumericCellValue.ToString();
                    }
                    catch
                    {
                        try
                        {
                            #region 這種方式處理可以保證100%無錯誤,但是效率太慢,一個文本公式讀取需要3秒
                            //IFormulaEvaluator formulaEvaluator;
                            //if (_excelVersion == "2007")
                            //{
                            //    formulaEvaluator = new XSSFFormulaEvaluator(workbook);
                            //}
                            //else
                            //{
                            //    formulaEvaluator = new HSSFFormulaEvaluator(workbook);
                            //}

                            //formulaEvaluator.EvaluateInCell(cell);
                            //var FormulaValue = cell.ToString();
                            #endregion

                            var FormulaValue = cell.StringCellValue.ToString();
                            return FormulaValue;
                        }
                        catch
                        {
                            return "";
                        }
                    }
                default:
                    return "=" + cell.CellFormula;
            }
        }


        /// <summary>
        /// 將excel中的數據導入到DataTable中
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="sheetName">excel工作薄sheet的名稱</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public static DataTable ReadTableFromExcel(string fileName, string sheetName = "", bool isFirstRowColumn = false)
        {
            //FileStream fs = null;
            try
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    ISheet sheet = null;
                    DataTable data = new DataTable();
                    int startRow = 0;
                    IWorkbook workbook = null;
                    if (fileName.Contains(".xlsx")) // 2007版本
                        workbook = new XSSFWorkbook(fs);
                    else if (fileName.Contains(".xls")) // 2003版本
                        workbook = new HSSFWorkbook(fs);

                    if (sheetName != null)
                    {
                        sheet = workbook.GetSheetAt(0);

                        int SheetCount = workbook.NumberOfSheets;//獲取表的數量
                        string[] SheetName = new string[SheetCount];//保存表的名稱
                        for (int i = 0; i < SheetCount; i++)
                        {
                            SheetName[i] = workbook.GetSheetName(i);

                        }
                        if (SheetName.Contains(sheetName))
                        {
                            sheet = workbook.GetSheet(sheetName);
                        }
                        else
                        {
                            sheet = workbook.GetSheetAt(0);
                        }
                        //if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet
                        //{
                        //sheet = workbook.GetSheet(sheetName);
                        //}
                    }
                    else
                    {
                        sheet = workbook.GetSheetAt(0);
                    }

                    if (sheet != null)
                    {
                        IRow firstRow = sheet.GetRow(0);
                        if (firstRow == null)
                        {
                            return data;
                        }
                        int cellCount = firstRow.LastCellNum; //一行最後一個cell的編號 即總的列數

                        if (isFirstRowColumn)
                        {
                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                            {
                                ICell cell = null;
                                cell = firstRow.GetCell(i);
                                if (cell != null)
                                {
                                    string cellValue = cell.StringCellValue;
                                    if (cellValue != null)
                                    {
                                        DataColumn column = new DataColumn(cellValue);
                                        data.Columns.Add(column);
                                    }
                                }
                            }

                            startRow = sheet.FirstRowNum + 1;
                        }
                        else
                        {
                            for (int column = 0; column < cellCount; column++)
                            {
                                data.Columns.Add($"Column{column}");
                            }

                            startRow = sheet.FirstRowNum;
                        }

                        //最後一列的標號
                        int rowCount = sheet.LastRowNum;
                        for (int i = startRow; i <= rowCount; ++i)
                        {
                            IRow row = sheet.GetRow(i);
                            if (row == null) continue; //沒有數據的行默認是null       

                            DataRow dataRow = data.NewRow();
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是null
                                    dataRow[j] = row.GetCell(j).ToString();
                            }
                            data.Rows.Add(dataRow);
                        }
                    }
                    return data;
                }
            }
            finally
            {
                //if (fs != null)
                //{
                //    fs.Dispose();
                //}
            }
        }

        /// <summary>
        /// 讀取單元格
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="sheetName">excel工作薄sheet的名稱</param>
        /// <param name="cell">單元格座標</param>
        /// <returns>返回的DataTable</returns>
        public static string ReadCell(string fileName, string sheetName = "", string cell = "")
        {
            FileStream fs = null;
            try
            {
                using (fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    ISheet sheet = null;
                    DataTable data = new DataTable();
                    int startRow = 0;
                    IWorkbook workbook = null;
                    if (fileName.Contains(".xlsx") || fileName.Contains(".ett") || fileName.Contains(".xlsm")) // 2007版本
                        workbook = new XSSFWorkbook(fs);
                    else if (fileName.Contains(".xls") || fileName.Contains(".et")) // 2003版本
                        workbook = new HSSFWorkbook(fs);

                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null)
                    {
                        throw new ArgumentException(ConfigStringHelper.ExcelError_NotSheet);
                    }
                    if (sheet != null)
                    {

                        CellReference cf = new CellReference(cell);

                        var irow = sheet.GetRow(cf.Row);
                        if (irow == null)
                        {
                            irow = sheet.CreateRow(cf.Row); ;
                        }
                        try
                        {
                            var cel = irow.GetCell(cf.Col);
                            if (cel == null)
                            {
                                cel = irow.CreateCell(cf.Col);
                            }
                            if (cel != null)
                            {
                                if (cel.CellType == CellType.Formula)
                                {
                                    cel.SetCellType(CellType.String);
                                }
                                return cel.ToString();
                            }
                        }
                        catch
                        {
                            throw new ArgumentException(ConfigStringHelper.ExcelError_CellExist);
                        }
                    }
                    return null;
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
            }
        }

        /// <summary>
        /// 讀取列
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="sheetName">excel工作薄sheet的名稱</param>
        /// <param name="column"></param>
        /// <returns>返回的DataTable</returns>
        public static string[] ReadColumn(string fileName, string sheetName, string column)
        {
            FileStream fs = null;
            try
            {
                using (fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    List<string> resultList = new List<string>();
                    ISheet sheet = null;

                    IWorkbook workbook = null;
                    if (fileName.Contains(".xlsx")) // 2007版本
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    else
                    {
                        workbook = new HSSFWorkbook(fs);
                    }

                    if (sheetName != null)
                    {
                        sheet = workbook.GetSheet(sheetName);
                        if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet
                        {
                            sheet = workbook.GetSheetAt(0);
                        }
                    }
                    else
                    {
                        sheet = workbook.GetSheetAt(0);
                    }

                    if (sheet != null)
                    {
                        CellReference cf = new CellReference(column);

                        for (int rownum = sheet.FirstRowNum; rownum <= sheet.LastRowNum; rownum++)
                        {
                            var row = sheet.GetRow(rownum);

                            var cell = row?.GetCell(cf.Col);
                            if (cell != null)
                            {
                                if (cell.CellType == CellType.Formula)
                                {
                                    cell.SetCellType(CellType.String);
                                }
                                resultList.Add(cell.ToString());
                            }
                        }
                    }
                    return resultList.ToArray();
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
            }
        }



        /// <summary>
        /// 讀取範圍
        /// </summary>
        [Obsolete]
        public static DataTable ReadRange(string fileName, string sheetName, string range, bool includeHeaders = false)
        {
            FileStream fs = null;
            try
            {
                using (fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    List<string> resultList = new List<string>();
                    ISheet sheet = null;

                    IWorkbook workbook = null;
                    if (fileName.Contains(".xlsx") || fileName.Contains(".ett") || fileName.Contains(".xlsm")) // 2007版本
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    else
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null)
                    {
                        throw new ArgumentException(ConfigStringHelper.ExcelError_NotSheet);
                    }
                    System.Data.DataTable dt = new System.Data.DataTable();
                    if (sheet != null)
                    {
                        try
                        {
                            CellRangeAddress cellRangeAddress = CellRangeAddress.ValueOf(range);
                            int firstcolumn = cellRangeAddress.FirstColumn;
                            int lastcolumn = cellRangeAddress.LastColumn;
                            int firstrow = cellRangeAddress.FirstRow;
                            int lastrow = cellRangeAddress.LastRow;


                            if (!range.Contains(":"))
                            {
                                if (lastcolumn == firstcolumn)
                                {
                                    IRow headrow = sheet.GetRow(firstrow);
                                    lastcolumn = headrow.Cells.Count;
                                }
                                if (lastrow == firstrow)
                                    lastrow = sheet.LastRowNum + 1;//得到總行數
                            }
                            int Column = lastcolumn - firstcolumn;
                            int startRow = firstrow;
                            List<int> columns = new List<int>();
                            //創建列頭
                            if (includeHeaders)
                            {
                                IRow firstRow = sheet.GetRow(startRow);
                                int cellCount = firstRow.LastCellNum;
                                for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                {
                                    ICell cell = null;
                                    cell = firstRow.GetCell(i);
                                    if (cell != null)
                                    {
                                        string cellValue = cell.StringCellValue;
                                        if (cellValue != null)
                                        {
                                            DataColumn column = new DataColumn(cellValue);
                                            dt.Columns.Add(column);
                                            columns.Add(i);
                                        }
                                    }
                                }

                                startRow = firstrow + 1;
                            }
                            else
                            {

                                for (int i = 0; i < Column; i++)
                                {
                                    dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                                    columns.Add(i);
                                }
                            }
                            //數據  
                            for (var i = startRow; i < lastrow; i++)
                            {
                                DataRow dr = dt.NewRow();
                                IRow row = sheet.GetRow(i);
                                if (row == null)
                                {
                                    row = sheet.CreateRow(i);
                                }
                                bool merged = false;
                                for (var j = firstcolumn; j < Column + firstcolumn; j++)
                                {

                                    ICell cell = row.GetCell(j);


                                    if (cell == null)
                                    {
                                        cell = row.CreateCell(j);
                                    }
                                    if (cell.IsMergedCell)  //檢測列的單元格是否合併
                                    {
                                        dr[j] = GetValueType(cell); //獲取單元格的值
                                        if (string.IsNullOrWhiteSpace(dr[j].ToString()) && j > 0)
                                        {
                                            if (merged)
                                            {
                                                dr[j] = dr[j - 1];
                                            }
                                        }
                                        merged = true;
                                    }
                                    else
                                    {
                                        merged = false;
                                        var firsLine = row.GetCell(j).ToString();
                                        dr[j - cellRangeAddress.FirstColumn] = GetValueType(row.GetCell(j));
                                    }
                                }
                                dt.Rows.Add(dr);
                            }
                        }
                        catch
                        {
                            throw new ArgumentException(ConfigStringHelper.ExcelError_ErrorRange);
                        }
                    }
                    return dt;
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
            }
        }

        /// <summary>
        /// 讀取範圍
        /// </summary>
        public static DataTable ReadRange(string fileName, string sheetName, string range, bool includeHeaders = false, bool isMergeColumn = false, bool isMergeRow = false)
        {
            FileStream fs = null;
            try
            {
                using (fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    List<string> resultList = new List<string>();
                    ISheet sheet = null;

                    IWorkbook workbook = null;
                    if (fileName.Contains(".xlsx") || fileName.Contains(".ett") || fileName.Contains(".xlsm")) // 2007版本
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    else
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null)
                    {
                        throw new ArgumentException("ExcelError_NotSheet");
                    }
                    System.Data.DataTable dt = new System.Data.DataTable();
                    if (sheet != null)
                    {
                        try
                        {
                            CellRangeAddress cellRangeAddress = CellRangeAddress.ValueOf(range);
                            int firstcolumn = cellRangeAddress.FirstColumn;
                            int lastcolumn = cellRangeAddress.LastColumn;
                            int firstrow = cellRangeAddress.FirstRow;
                            int lastrow = cellRangeAddress.LastRow;


                            if (!range.Contains(":"))
                            {
                                if (lastcolumn == firstcolumn)
                                {
                                    IRow headrow = sheet.GetRow(firstrow);
                                    lastcolumn = headrow.Cells.Count;
                                }
                                if (lastrow == firstrow)
                                    lastrow = sheet.LastRowNum + 1;//得到總行數
                            }
                            int Column = lastcolumn - firstcolumn;
                            int startRow = firstrow;
                            List<int> columns = new List<int>();
                            //創建列頭
                            if (includeHeaders)
                            {
                                IRow firstRow = sheet.GetRow(startRow);
                                int cellCount = firstRow.LastCellNum;
                                for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                {
                                    ICell cell = null;
                                    cell = firstRow.GetCell(i);
                                    if (cell != null)
                                    {
                                        string cellValue = cell.StringCellValue;
                                        if (cellValue != null)
                                        {
                                            DataColumn column = new DataColumn(cellValue);
                                            dt.Columns.Add(column);
                                            columns.Add(i);
                                        }
                                    }
                                }

                                startRow = firstrow + 1;
                            }
                            else
                            {

                                for (int i = 0; i < Column; i++)
                                {
                                    dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                                    columns.Add(i);
                                }
                            }
                            //數據  

                            for (var i = startRow; i < lastrow; i++)
                            {
                                DataRow dr = dt.NewRow();
                                IRow row = sheet.GetRow(i);
                                if (row == null)
                                {
                                    row = sheet.CreateRow(i);
                                }
                                bool merged = false;

                                for (var j = firstcolumn; j < Column + firstcolumn; j++)
                                {

                                    ICell cell = row.GetCell(j);


                                    if (cell == null)
                                    {
                                        cell = row.CreateCell(j);
                                    }
                                    if (cell.IsMergedCell)  //檢測列的單元格是否合併
                                    {

                                        dr[j - firstcolumn] = GetValueType(cell); //獲取單元格的值
                                        if (isMergeColumn)
                                        {
                                            if (string.IsNullOrWhiteSpace(dr[j - firstcolumn].ToString()) && j - firstcolumn > 0)
                                            {
                                                if (merged)
                                                {
                                                    dr[j - firstcolumn] = dr[j - firstcolumn - 1];

                                                }

                                            }
                                        }
                                        if (isMergeRow)
                                        {
                                            if (string.IsNullOrWhiteSpace(dr[j - firstcolumn].ToString()) && i - startRow > 0)
                                            {
                                                DataRow drRow = dt.Rows[dt.Rows.Count - 1];
                                                dr[j - firstcolumn] = drRow[j - firstcolumn];
                                            }
                                        }
                                        merged = true;
                                    }
                                    else
                                    {
                                        merged = false;
                                        var firsLine = row.GetCell(j).ToString();
                                        dr[j - firstcolumn] = GetValueType(row.GetCell(j));
                                    }
                                }
                                dt.Rows.Add(dr);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new ArgumentException("ExcelError_ErrorRange");
                        }
                    }
                    return dt;
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
            }
        }


        /// <summary>
        /// 讀取行
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="sheetName">excel工作薄sheet的名稱</param>
        /// <param name="rowIndex">行號</param>
        /// <param name="startColumnIndex">列號</param>
        /// <returns>返回的DataTable</returns>
        public static string[] ReadRow(string fileName, string sheetName, int rowIndex, int startColumnIndex)
        {
            FileStream fs = null;
            try
            {
                using (fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    List<string> resultList = new List<string>();
                    ISheet sheet = null;

                    IWorkbook workbook = null;
                    if (fileName.Contains(".xlsx") || fileName.Contains(".ett") || fileName.Contains(".xlsm")) // 2007版本
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    else
                    {
                        workbook = new HSSFWorkbook(fs);
                    }


                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null)
                    {
                        throw new ArgumentException(ConfigStringHelper.ExcelError_NotSheet);
                    }

                    if (sheet != null)
                    {
                        var row = sheet.GetRow(rowIndex);
                        if (row == null)
                        {
                            row = sheet.CreateRow(rowIndex);
                        }
                        if (row != null)
                        {
                            for (int columnNumber = startColumnIndex - 1; columnNumber < row.LastCellNum; columnNumber++)
                            {
                                var cell = row.GetCell(columnNumber);
                                if (cell == null)
                                {
                                    cell = row.CreateCell(columnNumber);
                                }
                                if (cell != null)
                                {
                                    if (cell.CellType == CellType.Formula)
                                    {
                                        cell.SetCellType(CellType.String);
                                    }
                                    resultList.Add(cell.ToString());
                                }
                            }
                        }
                    }
                    return resultList.ToArray();
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
            }
       
        }

        /// <summary>
        /// 寫入單元格
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="sheetName">excel工作薄sheet的名稱</param>
        /// <param name="cell">單元格座標</param>
        /// <param name="value">寫入的數據</param>
        /// <returns>返回的DataTable</returns>
        public static void WriteCell(string fileName, string sheetName, string cell, object value)
        {
            IWorkbook workbook = null;
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                if (fileName.Contains(".xlsx") || fileName.Contains(".ett") || fileName.Contains(".xlsm")) // 2007版本
                    workbook = new XSSFWorkbook(fs);
                else if (fileName.Contains(".xls") || fileName.Contains(".et")) // 2003版本
                    workbook = new HSSFWorkbook(fs);

                ISheet sheet = workbook.GetSheetAt(0); //獲取第一個工作表
                int SheetCount = workbook.NumberOfSheets;//獲取表的數量
                string[] SheetName = new string[SheetCount];//保存表的名稱
                for (int i = 0; i < SheetCount; i++)
                {
                    SheetName[i] = workbook.GetSheetName(i).ToLower();
                    //獲取sheet的索引
                }
                if (SheetName.Contains(sheetName.ToLower()))
                {
                    sheet = workbook.GetSheet(sheetName);
                }
                else
                {
                    throw new ArgumentException(ConfigStringHelper.ExcelError_NotSheet);
                }
                CellReference cf = new CellReference(cell);
                var row = sheet.GetRow(cf.Row);
                if (row == null)
                {
                    row = sheet.CreateRow(cf.Row);
                }
                try
                {
                    ICell icell = row.GetCell(cf.Col);
                    if (icell == null)
                    {
                        icell = row.CreateCell(cf.Col);
                    }

                    switch (icell.CellType)
                    {
                        case CellType.Formula:
                            icell.SetCellFormula(value.ToString());
                            break;
                        case CellType.Blank:
                        case CellType.Numeric:
                            if (value is DateTime)
                            {
                                icell.SetCellValue((DateTime)value);
                            }
                            else if (value is double)
                            {
                                icell.SetCellValue((double)value);
                            }
                            else
                            {
                                double doubleValue;

                                if (double.TryParse(value.ToString(), out doubleValue))
                                {
                                    icell.SetCellValue(doubleValue);
                                }
                                else
                                {
                                    icell.SetCellValue(value.ToString());
                                }
                            }
                            break;
                        case CellType.Boolean:
                            if (value is bool)
                            {
                                icell.SetCellValue((bool)value);
                            }
                            else
                            {
                                bool boolValue;
                                if (bool.TryParse(value.ToString(), out boolValue))
                                {
                                    icell.SetCellValue(boolValue);
                                }
                                else
                                {
                                    icell.SetCellValue(value.ToString());
                                }
                            }
                            break;
                        case CellType.Error:
                            if (value is byte)
                            {
                                icell.SetCellErrorValue((byte)value);
                            }
                            else
                            {
                                byte byteValue;
                                if (byte.TryParse(value.ToString(), out byteValue))
                                {
                                    icell.SetCellErrorValue(byteValue);
                                }
                                else
                                {
                                    icell.SetCellValue(value.ToString());
                                }
                            }
                            break;
                        case CellType.String:
                        default:
                            icell.SetCellValue(value.ToString());
                            break;
                    }
                    //Regex rx = new Regex(pattern);
                    //bool status = rx.IsMatch(value.ToString());
                    //if (status == true)
                    //{
                    //    //純數字
                    //    icell.SetCellValue(Convert.ToDouble(value));
                    //}
                    //else
                    //{
                    //    icell.SetCellValue(value.ToString());
                    //}
                }
                catch
                {
                    throw new Exception(ConfigStringHelper.ExcelError_CellExist);
                }
                //這一句使用NPOI必須加,如不加在修改完單元格的值後 excel不會自動更新公式的值
                sheet.ForceFormulaRecalculation = true;
            }
            //寫入到excel中
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                using (FileStream fs1 = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    byte[] _data = ms.ToArray();
                    fs1.Write(_data, 0, _data.Length);
                    fs1.Flush();
                    _data = null;
                }
            }

        }


        /// <summary>
        /// 寫入單元格
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="sheetName">excel工作薄sheet的名稱</param>
        /// <param name="cell">單元格座標</param>
        /// <param name="value">寫入的數據</param>
        /// <returns>返回的DataTable</returns>
        public static void WriteCell(ISheet sheet, string cell, object value)
        {
            CellReference cf = new CellReference(cell);
            var row = sheet.GetRow(cf.Row);
            if (row == null)
            {
                row = sheet.CreateRow(cf.Row);
            }
            try
            {
                if (value != null)
                {
                    ICell icell = row.GetCell(cf.Col);
                    if (icell == null)
                    {
                        icell = row.CreateCell(cf.Col);
                    }

                    switch (icell.CellType)
                    {
                        case CellType.Formula:
                            icell.SetCellFormula(value.ToString());
                            break;
                        case CellType.Numeric:
                            if (value is DateTime)
                            {
                                icell.SetCellValue((DateTime)value);
                            }
                            else if (value is double)
                            {
                                icell.SetCellValue((double)value);
                            }
                            else
                            {
                                double doubleValue;

                                if (double.TryParse(value.ToString(), out doubleValue))
                                {
                                    icell.SetCellValue(doubleValue);
                                }
                                else
                                {
                                    icell.SetCellValue(value.ToString());
                                }
                            }
                            break;
                        case CellType.Boolean:
                            if (value is bool)
                            {
                                icell.SetCellValue((bool)value);
                            }
                            else
                            {
                                bool boolValue;
                                if (bool.TryParse(value.ToString(), out boolValue))
                                {
                                    icell.SetCellValue(boolValue);
                                }
                                else
                                {
                                    icell.SetCellValue(value.ToString());
                                }
                            }
                            break;
                        case CellType.Error:
                            if (value is byte)
                            {
                                icell.SetCellErrorValue((byte)value);
                            }
                            else
                            {
                                byte byteValue;
                                if (byte.TryParse(value.ToString(), out byteValue))
                                {
                                    icell.SetCellErrorValue(byteValue);
                                }
                                else
                                {
                                    icell.SetCellValue(value.ToString());
                                }
                            }
                            break;
                        case CellType.String:
                        default:
                            icell.SetCellValue(value.ToString());
                            break;
                    }
                    //Regex rx = new Regex(pattern);
                    //bool status = rx.IsMatch(value.ToString());
                    //if (status == true)
                    //{
                    //    //純數字
                    //    icell.SetCellValue(Convert.ToDouble(value));
                    //}
                    //else
                    //{
                    //    icell.SetCellValue(value.ToString());
                    //}
                }
            }
            catch
            {
                throw new Exception(ConfigStringHelper.ExcelError_CellExist);
            }
            //這一句使用NPOI必須加,如不加在修改完單元格的值後 excel不會自動更新公式的值
            sheet.ForceFormulaRecalculation = true;
        }

        /// <summary>
        /// 寫入指定行
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="sheetName">excel工作薄sheet的名稱</param>
        /// <param name="rowIndex">單元格座標</param>
        /// <param name="data">寫入的數據</param>
        /// <returns>返回的DataTable</returns>
        public static void WriteRow(string fileName, string sheetName, int rowIndex, IEnumerable<object> data, int startColumnIndex, bool isInsertRow = false)
        {
            FileStream fs = null;
            try
            {
                IWorkbook workbook = null;
                ISheet sheet = null;
                using (fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    if (fileName.Contains(".xlsx") || fileName.Contains(".ett") || fileName.Contains(".xlsm")) // 2007版本
                        workbook = new XSSFWorkbook(fs);
                    else if (fileName.Contains(".xls") || fileName.Contains(".et")) // 2003版本
                        workbook = new HSSFWorkbook(fs);
                }
                if (sheetName != null)
                {
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null)
                    {
                        throw new Exception(ConfigStringHelper.ExcelError_NotSheet);
                    }
                }
                else
                {
                    //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet
                    sheet = workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    var row = sheet.GetRow(rowIndex);

                    if (row == null)
                    {
                        row = sheet.CreateRow(rowIndex);
                    }

                    if (row != null)
                    {
                        int columnIndex = startColumnIndex;
                        foreach (var item in data)
                        {
                            if (item != null)
                            {
                                ICell icell = row.CreateCell(columnIndex);
                                if (icell == null)
                                {
                                    icell = row.CreateCell(columnIndex);
                                }
                                Regex rx = new Regex(pattern);
                                bool status = rx.IsMatch(item.ToString());
                                if (status == true)
                                {
                                    //純數字
                                    icell.SetCellValue(Convert.ToDouble(item));
                                }
                                else
                                {
                                    icell.SetCellValue(item.ToString());
                                }
                            }
                            columnIndex++;
                        }
                        using (MemoryStream ms = new MemoryStream())
                        {
                            workbook.Write(ms);
                            using (FileStream fs1 = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                            {
                                byte[] _data = ms.ToArray();
                                fs1.Write(_data, 0, _data.Length);
                                fs1.Flush();
                                _data = null;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
            }
        }

        /// <summary>
        /// 寫入指定列
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="sheetName">excel工作薄sheet的名稱</param>
        /// <param name="columnName">單元格座標</param>
        /// <param name="ColumnIndex">列索引</param>
        /// <param name="data">寫入的數據</param>
        /// <param name="StartRowIndex">起始行號 從零開始</param>
        /// <returns>返回的DataTable</returns>
        public static void WriteColumn(string fileName, string sheetName, string columnName, int ColumnIndex, IEnumerable<object> data, int StartRowIndex, bool insertColumn = false)
        {
            string cell_Value = "";
            List<object> inserValues = new List<object>();
            foreach (var item in data)
            {
                inserValues.Add(item);
            }
            IWorkbook workbook = null;
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                try
                {
                    ISheet sheet = null;
                    if (fileName.Contains(".xlsx") || fileName.Contains(".ett") || fileName.Contains(".xlsm")) // 2007版本
                        workbook = new XSSFWorkbook(fs);
                    else if (fileName.Contains(".xls") || fileName.Contains(".et")) // 2003版本
                        workbook = new HSSFWorkbook(fs);

                    if (sheetName != null)
                    {
                        sheet = workbook.GetSheet(sheetName);
                        if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet
                        {
                            throw new Exception(ConfigStringHelper.ExcelError_NotSheet);
                        }
                    }
                    else
                    {
                        sheet = workbook.GetSheetAt(0);
                    }

                    if (sheet != null)
                    {
                        bool status = false;
                        var rowCount = sheet.LastRowNum + 1;//得到總行數
                        if (!string.IsNullOrEmpty(columnName))
                        {
                            IRow row = sheet.GetRow(0);
                            if (row == null)
                            {
                                row = sheet.CreateRow(0);
                            }
                            for (var j = 0; j < row.Cells.Count; j++)
                            {

                                ICell cell = row.GetCell(j);
                                if (cell == null)
                                {
                                    cell = row.CreateCell(j);
                                }
                                var firsLine = row.GetCell(j).ToString();
                                if (firsLine == columnName)
                                {
                                    if (status == false)
                                    {
                                        cell_Value = columnName;
                                        status = true;
                                        ColumnIndex = j;
                                    }
                                    //記錄所在的列,只記錄一次如果出現多個同名列只計算第一列
                                }
                            }
                        }
                        if (string.IsNullOrEmpty(cell_Value) && !string.IsNullOrEmpty(columnName))
                        {
                            throw new ArgumentNullException(ConfigStringHelper.ExcelError_SheetNotcolumnName);
                        }
                        int targetColumn = StartRowIndex - 1;
                        int k = 0;
                        int Index = 0;
                        if (status == true)
                        {
                            Index = ColumnIndex;
                        }
                        else
                        {
                            Index = ColumnIndex - 1;
                        }
                        for (int rows = 0; rows < inserValues.Count(); rows++)
                        {
                            IRow row = sheet.GetRow(targetColumn);
                            if (row == null)
                            {
                                row = sheet.CreateRow(targetColumn);
                            }
                            ICell cell = row.GetCell(Index);
                            if (cell == null)
                            {
                                cell = row.CreateCell(Index);
                            }
                            Regex rx = new Regex(pattern);
                            bool statued = rx.IsMatch(inserValues[k].ToString());
                            if (statued == true)
                            {
                                //純數字
                                cell.SetCellValue(Convert.ToDouble(inserValues[k]));
                            }
                            else
                            {
                                cell.SetCellValue(inserValues[k].ToString());
                            }
                            k++;
                            targetColumn++;
                        }

                    }
                    //這一句使用NPOI必須加,如不加在修改完單元格的值後 excel不會自動更新公式的值
                    sheet.ForceFormulaRecalculation = true;
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Dispose();
                    }
                }
            }
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    byte[] _data = ms.ToArray();
                    fs.Write(_data, 0, _data.Length);
                    fs.Flush();
                    _data = null;
                }
            }


        }


        public static void InsertRow(string FilePath, string sheetName, IEnumerable<object> data, int insertrowIndex, int startColumnIndex)
        {
            List<object> inserValues = new List<object>();
            foreach (var item in data)
            {
                inserValues.Add(item);
            }
            IWorkbook workbook = null;
            //讀取流
            using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                if (FilePath.IndexOf(".xlsx") > 0 || FilePath.IndexOf(".ett") > 0 || FilePath.IndexOf(".xlsm") > 0)
                {  //2007版本的excel
                    workbook = new XSSFWorkbook(fs);
                }
                else if (FilePath.IndexOf(".xls") > 0 || FilePath.IndexOf(".et") > 0) //2003版本的excel
                {
                    workbook = new HSSFWorkbook(fs);
                }
                ISheet sheet = workbook.GetSheetAt(0); //獲取第一個工作表
                int SheetCount = workbook.NumberOfSheets;//獲取表的數量
                string[] SheetName = new string[SheetCount];//保存表的名稱
                for (int i = 0; i < SheetCount; i++)
                {
                    SheetName[i] = workbook.GetSheetName(i).ToLower();
                    //獲取sheet的索引
                }
                if (string.IsNullOrEmpty(sheetName))
                {
                    //沒有填寫默認sheet,則獲取第一個sheet
                    sheet = workbook.GetSheetAt(0);
                }
                else
                {
                    if (SheetName.Contains(sheetName.ToLower()))
                    {
                        sheet = workbook.GetSheet(sheetName);
                    }
                    else
                    {
                        throw new ArgumentException(ConfigStringHelper.ExcelError_NotSheet);
                    }
                }
                //插入行
                sheet.ShiftRows(insertrowIndex - 1, sheet.LastRowNum + insertrowIndex - 1, 1, true, true);
                IRow row = sheet.GetRow(insertrowIndex - 1);
                if (row == null)
                {
                    row = sheet.CreateRow(insertrowIndex - 1);
                }
                for (var j = 0; j < inserValues.Count; j++)
                {
                    ICell cell = row.GetCell(j);
                    if (cell == null)
                    {
                        cell = row.CreateCell(j);
                    }
                    if (inserValues[j] != null)
                    {
                        Regex rx = new Regex(pattern);
                        bool status = rx.IsMatch(inserValues[j].ToString());
                        if (status == true)
                        {
                            //純數字
                            cell.SetCellValue(Convert.ToDouble(inserValues[j]));
                        }
                        else
                        {
                            cell.SetCellValue(inserValues[j].ToString());
                        }
                    }

                }
            }
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                using (FileStream fs = new FileStream(FilePath, FileMode.Create, FileAccess.Write))
                {
                    byte[] _data = ms.ToArray();
                    fs.Write(_data, 0, _data.Length);
                    fs.Flush();
                    _data = null;
                }
            }
        }


        //插入空行
        private static void InsertRowCount(string FilePath, string sheetName, int rowCount, int insertrowIndex, int startColumnIndex)
        {

            IWorkbook workbook = null;
            //讀取流
            using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                if (FilePath.IndexOf(".xlsx") > 0 || FilePath.IndexOf(".ett") > 0 || FilePath.IndexOf(".xlsm") > 0)
                {  //2007版本的excel
                    workbook = new XSSFWorkbook(fs);
                }
                else if (FilePath.IndexOf(".xls") > 0 || FilePath.IndexOf(".et") > 0) //2003版本的excel
                {
                    workbook = new HSSFWorkbook(fs);
                }
                ISheet sheet = workbook.GetSheetAt(0); //獲取第一個工作表
                int SheetCount = workbook.NumberOfSheets;//獲取表的數量
                string[] SheetName = new string[SheetCount];//保存表的名稱
                for (int i = 0; i < SheetCount; i++)
                {
                    SheetName[i] = workbook.GetSheetName(i).ToLower();
                    //獲取sheet的索引
                }
                if (string.IsNullOrEmpty(sheetName))
                {
                    //沒有填寫默認sheet,則獲取第一個sheet
                    sheet = workbook.GetSheetAt(0);
                }
                else
                {
                    if (SheetName.Contains(sheetName.ToLower()))
                    {
                        sheet = workbook.GetSheet(sheetName);
                    }
                    else
                    {
                        throw new ArgumentException(ConfigStringHelper.ExcelError_NotSheet);
                    }
                }
                //插入行
                sheet.ShiftRows(insertrowIndex - 1, sheet.LastRowNum + insertrowIndex - 1, 1, true, true);
            }
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                using (FileStream fs = new FileStream(FilePath, FileMode.Create, FileAccess.Write))
                {
                    byte[] _data = ms.ToArray();
                    fs.Write(_data, 0, _data.Length);
                    fs.Flush();
                    _data = null;
                }
            }
        }


        //實現在指定列前插入列
        /// <summary>
        /// 
        /// </summary>
        /// <param name="FilePath">excel路徑</param>
        /// <param name="sheetName">sheet名稱</param>
        /// <param name="data">數據源</param>
        /// <param name="columnName">指定的內容列名</param>
        /// <param name="insertColumnIndex">列索引</param>
        /// <param name="StartRowIndex">從第幾行開始</param>
        public static void InsertColumn(string FilePath, string sheetName, IEnumerable<object> data, string columnName, int insertColumnIndex, int StartRowIndex)
        {
            string cell_Value = "";
            List<object> inserValues = new List<object>();
            foreach (var item in data)
            {
                inserValues.Add(item);
            }
            IWorkbook workbook = null;
            //讀取流
            using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                if (FilePath.IndexOf(".xlsx") > 0 || FilePath.IndexOf(".ett") > 0 || FilePath.IndexOf(".xlsm") > 0)
                {  //2007版本的excel
                    workbook = new XSSFWorkbook(fs);
                }
                else if (FilePath.IndexOf(".xls") > 0 || FilePath.IndexOf(".et") > 0) //2003版本的excel
                {
                    workbook = new HSSFWorkbook(fs);
                }
                bool SheetStatus = false;
                ISheet sheet = workbook.GetSheetAt(0); //獲取第一個工作表
                int SheetCount = workbook.NumberOfSheets;//獲取表的數量
                string[] SheetName = new string[SheetCount];//保存表的名稱

                for (int i = 0; i < SheetCount; i++)
                {
                    SheetName[i] = workbook.GetSheetName(i).ToLower();
                    //獲取sheet的索引
                }
                if (string.IsNullOrEmpty(sheetName))
                {
                    //沒有填寫默認sheet,則獲取第一個sheet
                    sheet = workbook.GetSheetAt(0);
                    SheetStatus = true;
                }
                else
                {

                    if (SheetName.Contains(sheetName.ToLower()))
                    {
                        sheet = workbook.GetSheet(sheetName);
                    }
                    else
                    {
                        throw new ArgumentException(ConfigStringHelper.ExcelError_NotSheet);
                    }
                }
                bool status = false;
                var rowCount = sheet.LastRowNum + 1;//得到總行數
                if (!string.IsNullOrEmpty(columnName))
                {
                    IRow row = sheet.GetRow(0);
                    if (row == null)
                    {
                        row = sheet.CreateRow(0);
                    }
                    for (var j = 0; j < row.Cells.Count; j++)
                    {

                        ICell cell = row.GetCell(j);
                        if (cell == null)
                        {
                            cell = row.CreateCell(j);
                        }
                        var firsLine = row.GetCell(j).ToString();
                        if (firsLine == columnName)
                        {
                            if (status == false)
                            {
                                cell_Value = columnName;
                                status = true;
                                insertColumnIndex = j;
                            }
                            //記錄所在的列,只記錄一次如果出現多個同名列只計算第一列
                        }
                    }
                }
                if (string.IsNullOrEmpty(cell_Value) && !string.IsNullOrEmpty(columnName))
                {
                    throw new ArgumentNullException(ConfigStringHelper.ExcelError_SheetNotcolumnName);
                }
                //z這裏遍歷得到最大列數,因爲存在第一行殘缺爲空的情況
                List<int> array = new List<int>();
                for (var i = 0; i < rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row == null)
                    {
                        row = sheet.CreateRow(i);
                    }
                    //array.Add(row.Cells.Count);//獲取有效列
                    array.Add(row.LastCellNum);//獲取所有列
                }
                var maxValue = array.Max();//得到最大列數
                                           //創建列頭
                System.Data.DataTable dt = new System.Data.DataTable();
                List<int> columns = new List<int>();
                for (int i = 0; i < maxValue; i++)
                {
                    dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    columns.Add(i);
                }

                //數據  
                for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                    }
                    dt.Rows.Add(dr);
                }
                int Index = 0;
                if (status == true)
                {
                    Index = insertColumnIndex;
                }
                else
                {
                    Index = insertColumnIndex - 1;
                }
                //在指定的列前插入列
                dt.Columns.Add("custom999").SetOrdinal(Index);
                int J = 0;
                int StartIndex = StartRowIndex - 1;
                for (int k = StartIndex; k < inserValues.Count() + StartIndex; k++)
                {
                    if (dt.Rows.Count + StartIndex <= k)
                    {
                        DataRow dr = dt.NewRow();
                        dt.Rows.Add(dr);
                    }
                    dt.Rows[k]["custom999"] = inserValues[J];
                    J++;
                }
                //因爲使用datatable處理所以要先刪除原有sheet,創建新sheet導入數據
                if (SheetStatus == true)
                {
                    //說明是使用默認sheet
                    workbook.RemoveSheetAt(workbook.GetSheetIndex(SheetName[0]));
                    sheet = workbook.CreateSheet(SheetName[0]);
                }
                else
                {
                    workbook.RemoveSheetAt(workbook.GetSheetIndex(sheetName));
                    sheet = workbook.CreateSheet(sheetName);
                }
                int WriteRowCount = 0;
                //寫入數據
                for (int row = 0; row < dt.Rows.Count; row++)
                {
                    IRow newRow;
                    newRow = sheet.CreateRow(WriteRowCount);
                    for (int column = 0; column < dt.Columns.Count; column++)
                    {

                        newRow.CreateCell(column).SetCellValue(dt.Rows[row][column].ToString());

                    }
                    WriteRowCount++;
                }
            }
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                using (FileStream fs = new FileStream(FilePath, FileMode.Create, FileAccess.Write))
                {
                    byte[] _data = ms.ToArray();
                    fs.Write(_data, 0, _data.Length);
                    fs.Flush();
                    _data = null;
                }
            }
        }

        public static DataTable ReadTable(string FilePath, string sheetName, int startIndex, int endIndex)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook = null;
            using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                if (startIndex > 0)
                {
                    if (startIndex > endIndex)
                    {
                        throw new ArgumentException(ConfigStringHelper.ExcelError_ArgumentExceptionRowJudge);
                    }
                }
                else
                {
                    if (endIndex > 1)
                    {
                        throw new ArgumentException(ConfigStringHelper.ExcelError_ArgumentExceptionRowNotStartIndex);
                    }
                }
                if (FilePath.IndexOf(".xlsx") > 0 || FilePath.IndexOf(".ett") > 0 || FilePath.IndexOf(".xlsm") > 0)
                {  //2007版本的excel
                    workbook = new XSSFWorkbook(fs);
                }
                else if (FilePath.IndexOf(".xls") > 0 || FilePath.IndexOf(".et") > 0) //2003版本的excel
                {
                    workbook = new HSSFWorkbook(fs);
                }
                ISheet sheet = workbook.GetSheetAt(0);//獲取工作表
                int SheetCount = workbook.NumberOfSheets;//獲取表的數量
                string[] SheetName = new string[SheetCount];//保存表的名稱
                for (int i = 0; i < SheetCount; i++)
                {
                    SheetName[i] = workbook.GetSheetName(i).ToLower();
                    //獲取sheet的索引
                }
                if (SheetName.Contains(sheetName.ToLower()))
                {
                    sheet = workbook.GetSheet(sheetName);
                }
                else
                {
                    throw new ArgumentException(ConfigStringHelper.ExcelError_NotSheet);
                }
                var rowCount = sheet.LastRowNum + 1;//得到總行數
                //z這裏遍歷得到最大列數,因爲存在第一行殘缺爲空的情況
                List<int> array = new List<int>();
                for (var i = 0; i < rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row == null)
                    {
                        row = sheet.CreateRow(i);
                    }
                    array.Add(row.LastCellNum);//獲取所有列(包含空列以及殘缺)
                }
                var maxValue = array.Max();//得到最大列數
                int Index = 0;
                int Endex = 0;
                List<int> columns = new List<int>();
                for (int i = 0; i < maxValue; i++)
                {
                    dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    columns.Add(i);
                }
                if (startIndex > 1)
                {
                    Index = startIndex;
                }
                if (endIndex > 1)
                {
                    Endex = endIndex;
                }
                else
                {
                    Endex = sheet.LastRowNum;
                }
                //數據  
                for (int i = Index; i <= Endex; i++)
                {
                    DataRow dr = dt.NewRow();
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                    }
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }

    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章