1. 程式人生 > >C#之NPOI處理Excel

C#之NPOI處理Excel

簡介:

NPOI是源於一個用於讀取xls,doc,ppt文件的POI 專案,POI是Java專案,後面因為有.Net的市場,於是將POI移植到.Net上便是NPOI。

特點:

對環境沒有過多要求,不需要Windows系統預裝office環境。特別適用於伺服器上,一般伺服器不會裝office。

缺點:

 在Excel資料量大的情況下,渲染Excel樣式效能較慢。

具體實現:

1、dll下載以及引用

引用下面幾個dll

2、引用名稱空間

using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;

3、具體實現

1、全域性變數

        #region 私有變數
        /// <summary>
        /// Excel檔案工作簿
        /// </summary>
        private static IWorkbook _workbook;

        /// <summary>
        /// Excel檔案工作表
        /// </summary>
        private static ISheet _worksheet;
        
        /// <summary>
        /// Excel檔案路徑
        /// </summary>
        private static string _filePath = string.Empty;

        /// <summary>
        /// excel版本
        /// 預設為2007
        /// </summary>
        private static string _excelVersion = "2007";
        #endregion

2、呼叫方法

/// <summary>
        /// 建立一個空白的Excel檔案
        /// 用於寫Excel
        /// 寫的時候,還需要新增Sheet
        /// </summary>
        /// <param name="strFilePath">檔案路徑</param>
        public static void CreateExcel(string strFilePath)
        {
            _filePath = strFilePath;
            using (FileStream fs = new FileStream(strFilePath, FileMode.Create, FileAccess.ReadWrite))
            {
                if (strFilePath.EndsWith(".xls"))//97-2003低版本的
                {
                    _workbook = new HSSFWorkbook();
                    _excelVersion = "2003";
                }
                else//高版本的2007
                {
                    _workbook = new XSSFWorkbook();
                    _excelVersion = "2007";
                }
                CreateSheet();

                fs.Close();
            }
        }




        /// <summary>
        /// 儲存Excel
        /// </summary>
        public static void SaveExcel()
        {
            if (!File.Exists(_filePath))
            {
                throw new Exception(string.Format("檔案:{0},不存在!", _filePath));
            }
            using (FileStream fsOut = new FileStream(_filePath, FileMode.Create, FileAccess.Write))
            {
                _workbook.Write(fsOut); //寫入到當前已經開啟的excel檔案
                fsOut.Close();
            }
        }

        /// <summary>
        /// Excel檔案另存為
        /// </summary>
        /// <param name="strSavePath">檔案命名</param>
        public static void SaveExcelAs(string strSavePath)
        {
            if (!Directory.Exists(Path.GetDirectoryName(strSavePath)))
            {
                throw new Exception(string.Format("檔案另存為的目錄:{0},不存在", Path.GetDirectoryName(strSavePath)));
            }
            
            using (FileStream fsOut = new FileStream(strSavePath, FileMode.Create, FileAccess.Write))
            {
                _workbook.Write(fsOut); //寫入到excel檔案
                fsOut.Close();
            }
        }

        /// <summary>
        /// 關閉Exel檔案
        /// 部分變數初始化
        /// </summary>
        public static void CloseExcel()
        {
            if (_workbook != null)
            {
                _workbook.Close();
                _workbook = null;
            }

            if (_worksheet != null)
            {
                _workbook = null;
            }

            GC.Collect();
        }

        /// <summary>
        /// 設定sheet
        /// 預設的活動的sheet
        /// </summary>
        /// <returns></returns>
        public static void SetSheet()
        {
            if (_workbook == null)
            {
                throw new Exception("工作簿為null,不能獲取sheet");
            }
            ISheet sheet = _workbook.GetSheetAt(_workbook.ActiveSheetIndex);
            if (sheet == null)
            {
                throw new Exception("獲取到的sheet為null");
            }
            _worksheet = sheet;
        }

        /// <summary>
        /// 設定指定索引的sheet
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public static void SetSheet(int index)
        {
            if (_workbook == null)
            {
                throw new Exception("工作簿為null,不能獲取sheet");
            }
            if (index >= GetSheetNum() || index < 0)
            {
                throw new Exception(string.Format("Sheet索引[{0}]不能大於等於Sheet數量[{1}],或者小於0", index, GetSheetNum()));
            }
            ISheet sheet = _workbook.GetSheetAt(index);
            if (sheet == null)
            {
                throw new Exception("獲取到的sheet為null");
            }
            _worksheet = sheet;
        }

        /// <summary>
        /// 設定指定名稱的sheet
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        /// </summary>
        /// <param name="strSheetName"></param>
        /// <returns></returns>
        public static void SetSheet(string strSheetName)
        {
            if (_workbook == null)
            {
                throw new Exception("工作簿為null,不能獲取sheet");
            }

            ISheet sheet = _workbook.GetSheet(strSheetName);
            if (sheet == null)
            {
                throw new Exception("獲取到的sheet為null");
            }
            _worksheet = sheet;
        }

        /// <summary>
        /// 獲取工作表數量
        /// </summary>
        /// <returns></returns>
        public static int GetSheetNum()
        {
            if (_workbook == null)
            {
                throw new Exception("工作簿為null,不能獲取sheet");
            }
            return _workbook.NumberOfSheets;
           
            //CellRangeAddress.ValueOf(range);
            //ICellStyle cellStyle = _workbook.CreateCellStyle();
            
        }

        /// <summary>
        /// 建立sheet
        /// </summary>
        public static void CreateSheet()
        {
            if (_workbook == null)
            {
                throw new Exception("工作簿為null,不能獲取sheet");
            }
            _worksheet = _workbook.CreateSheet();
        }

        /// <summary>
        /// 建立指定名稱的sheet
        /// </summary>
        /// <param name="strSheetName"></param>
        public static void CreateSheet(string strSheetName)
        {
            if (_workbook == null)
            {
                throw new Exception("工作簿為null,不能獲取sheet");
            }
            _worksheet= _workbook.CreateSheet(strSheetName);
        }

        /// <summary>
        /// 刪除指定索引的sheet
        /// </summary>
        /// <param name="index"></param>
        public static void DeleteSheet(int index)
        {
            if (index >= GetSheetNum() || index < 0)
            {
                throw new Exception(string.Format("Sheet索引[{0}]不能大於等於Sheet數量[{1}],或者小於0", index, GetSheetNum()));
            }
            _workbook.RemoveSheetAt(index);
        }

        /// <summary>
        /// 獲取總行數
        /// </summary>
        /// <returns></returns>
        public static int GetRowNum()
        {
            if (_worksheet == null)
            {
                throw new Exception("工作表不能為null");
            }
            return _worksheet.LastRowNum;
        }

        /// <summary>
        /// 獲取指定行的總列數
        /// </summary>
        /// <param name="rowIndex">從1開始</param>
        /// <returns></returns>
        public static int GetColNum(int rowIndex)
        {
            if (rowIndex < 1)
            {
                throw new Exception("引數rowInde不能小於1");
            }
            if (_worksheet == null)
            {
                throw new Exception("工作表不能為null");
            }
            return _worksheet.GetRow(rowIndex-1).LastCellNum;
        }

        /// <summary>
        /// 獲取指定單元格的值
        /// </summary>
        /// <param name="rowIndex">從1開始</param>
        /// <param name="colIndex">從1開始</param>
        /// <returns></returns>
        public static string GetCellValue(int rowIndex, int colIndex)
        {
            if (rowIndex < 1 || colIndex < 1)
            {
                throw new Exception("引數rowIndex或colIndex不能小於1");
            }
            if (_worksheet == null)
            {
                throw new Exception("工作表不能為null");
            }
            object result = "";
            if (_worksheet.GetRow(rowIndex - 1) == null)
            {
                return "";
            }
            ICell cell = _worksheet.GetRow(rowIndex - 1).GetCell(colIndex - 1);
            if (cell != null)
            {
                switch (cell.CellType)//需要根據不同的單元格格式獲取值,有公式的按照公式計算出結果
                {
                    case CellType.Blank:
                        result = "";
                        break;
                    case CellType.Boolean:
                        result = cell.BooleanCellValue;
                        break;
                    case CellType.Error:
                        result = cell.ErrorCellValue;
                        break;
                    case CellType.Formula://公式
                        try
                        {
                            IFormulaEvaluator formulaEvaluator;
                            if (_excelVersion == "2007")
                            {
                                formulaEvaluator = new XSSFFormulaEvaluator(_workbook);
                            }
                            else
                            {
                                formulaEvaluator = new HSSFFormulaEvaluator(_workbook);
                            }

                            formulaEvaluator.EvaluateInCell(cell);
                            result = cell.ToString();
                        }
                        catch
                        {
                            if (DateUtil.IsCellDateFormatted(cell))//日期
                            {
                                result = cell.DateCellValue;
                            }
                            else
                            {
                                result = cell.NumericCellValue;
                            }
                        }
                        break;
                    case CellType.Numeric:
                        if (DateUtil.IsCellDateFormatted(cell))//日期
                        {
                            result = cell.DateCellValue;
                        }
                        else
                        {
                            result = cell.NumericCellValue;
                        }
                        break;
                    case CellType.String:
                        result = cell.StringCellValue.Trim();
                        break;
                    case CellType.Unknown:
                        result = cell.ToString();
                        break;
                    default:
                        break;
                }
                return result.ToString();
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 獲取單元格的值
        /// </summary>
        /// <param name="rowIndex">行</param>
        /// <param name="colIndex">列</param>
        /// <returns></returns>
        public static string GetCellValueNotForm(int rowIndex, int colIndex)
        {
            //不需要根據不同單元格的格式獲取值。
            if (rowIndex < 1 || colIndex < 1)
            {
                throw new Exception("引數rowIndex或colIndex不能小於1");
            }
            if (_worksheet == null)
            {
                throw new Exception("工作表不能為null");
            }
            object result = "";

            if (_worksheet.GetRow(rowIndex - 1) == null)
            {
                return "";
            }
            ICell cell = _worksheet.GetRow(rowIndex - 1).GetCell(colIndex - 1);
            if (cell != null)
            {
                return cell.ToString();
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 設定指定單元格的值
        /// </summary>
        /// <param name="rowIndex">從1開始</param>
        /// <param name="colIndex">從1開始</param>
        /// <param name="value">值</param>
        /// <param name="valueType">值型別,預設為1 
        /// 0:數字格式
        /// 1:字串格式
        /// 2:公式格式
        /// 3:日期格式
        /// 4:布林型別值
        /// </param>
        public static void SetCellValue(int rowIndex, int colIndex, string value,int valueType=1)
        {
            if (rowIndex < 1 || colIndex < 1)
            {
                throw new Exception("引數rowIndex或colIndex不能小於1");
            }
            if (_worksheet == null)
            {
                throw new Exception("工作表不能為null");
            }

            IRow row = _worksheet.GetRow(rowIndex - 1);
            if (row == null)//為NULL,則建立行
            {
                row = _worksheet.CreateRow(rowIndex - 1);
            }

            ICell cell = row.GetCell(colIndex - 1);
            if (cell == null)//為NULL,則建立單元格
            {
                cell = row.CreateCell(colIndex - 1);
            }
            
            switch (valueType)
            {
                case 0://數字格式
                    cell.SetCellValue(string.IsNullOrEmpty(value) ? 0 : double.Parse(value));
                    break;
                case 1://字串格式,預設值
                    cell.SetCellValue(value);
                    break;
                case 2://公式
                    cell.SetCellFormula(value);
                    break;
                case 3://日期時間
                    cell.SetCellValue(string.IsNullOrEmpty(value) ? DateTime.Now : Convert.ToDateTime(value));
                    break;
                case 4://日期時間
                    cell.SetCellValue(string.IsNullOrEmpty(value)?false:Convert.ToBoolean(value));
                    break;
                default:
                    cell.SetCellValue(value);
                    break;
            }
        }

一起分享知識~