.Net Core 使用 NPOI 導入Excel

因爲以前在網上查閱一些資料發現老是不能編譯經過,不能正常使用,現把能正常使用的代碼貼出:數組

/// <summary>
   /// Excel導入幫助類
   /// </summary>
    public class ImportExcelUtil<T> where T : new()
    {
        //合法文件擴展名
        private static List<string> extName = new List<string>() { ".xls", ".xlsx" };
        /// <summary>
        /// 導入Excel內容讀取到List<T>/// </summary>
        /// <param name="file">導入Execl文件</param>
        /// <param name="sheetName">指定讀取excel工做薄sheet的名稱</param>
        /// <returns>List<T></returns>
        public static List<T> InputExcel(IFormFile file, string sheetName = null)
        {
            //獲取文件後綴名
            string type = Path.GetExtension(file.FileName);
            //判斷是否導入合法文件
            if(!extName.Contains(type))
            {
                return null;
            }
            //轉成爲文件流
            MemoryStream ms = new MemoryStream();
            file.CopyTo(ms);
            ms.Seek(0, SeekOrigin.Begin);
            //實例化T數組
            List<T> list = new List<T>();
            //獲取數據
            list = InputExcel(ms, sheetName);
            return list;
        }

        /// <summary>
        /// 將Excel文件內容讀取到List<T>/// </summary>
        /// <param name="fileName">文件完整路徑名</param>
        /// <param name="sheetName">指定讀取excel工做薄sheet的名稱</param>
        /// <param name="isFirstRowColumn">第一行是不是DataTable的列名:true=是,false=否</param>
        /// <returns>List<T></returns>
        public static List<T> InputExcel(string fileName, string sheetName = null)
        {
            if (!File.Exists(fileName))
            {
                return null;
            }
            //根據指定路徑讀取文件
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            //實例化T數組
            List<T> list = new List<T>();
            //獲取數據
            list = InputExcel(fs, sheetName);

            return list;
        }

        /// <summary>
        /// 將Excel文件內容讀取到List<T>/// </summary>
        /// <param name="fileStream">文件流</param>
        /// <param name="sheetName">指定讀取excel工做薄sheet的名稱</param>
        /// <returns>List<T></returns>
        private static List<T> InputExcel(Stream fileStream, string sheetName = null)
        {
            //建立Excel數據結構
            IWorkbook workbook = WorkbookFactory.Create(fileStream);
            //若是有指定工做表名稱
            ISheet sheet = null;
            if (!string.IsNullOrEmpty(sheetName))
            {
                sheet = workbook.GetSheet(sheetName);
                //若是沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet
                if (sheet == null)
                {
                    sheet = workbook.GetSheetAt(0);
                }
            }
            else
            {
                //若是沒有指定的sheetName,則嘗試獲取第一個sheet
                sheet = workbook.GetSheetAt(0);
            }
            //實例化T數組
            List<T> list = new List<T>();
            if (sheet != null)
            {
                //一行最後一個cell的編號 即總的列數
                IRow cellNum = sheet.GetRow(0);
                int num = cellNum.LastCellNum;
                //獲取泛型對象T的全部屬性
                var propertys = typeof(T).GetProperties();
                //每行轉換爲單個T對象
                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    var obj = new T();
                    for (int j = 0; j < num; j++)
                    {
                        //沒有數據的單元格都默認是null
                        ICell cell = row.GetCell(j);
                        if (cell != null)
                        {
                            var value = row.GetCell(j).ToString();
                            string str = (propertys[j].PropertyType).FullName;
                            if (str == "System.String")
                            {
                                propertys[j].SetValue(obj, value, null);
                            }
                            else if (str == "System.DateTime")
                            {
                                DateTime pdt = Convert.ToDateTime(value, CultureInfo.InvariantCulture);
                                propertys[j].SetValue(obj, pdt, null);
                            }
                            else if (str == "System.Boolean")
                            {
                                bool pb = Convert.ToBoolean(value);
                                propertys[j].SetValue(obj, pb, null);
                            }
                            else if (str == "System.Int16")
                            {
                                short pi16 = Convert.ToInt16(value);
                                propertys[j].SetValue(obj, pi16, null);
                            }
                            else if (str == "System.Int32")
                            {
                                int pi32 = Convert.ToInt32(value);
                                propertys[j].SetValue(obj, pi32, null);
                            }
                            else if (str == "System.Int64")
                            {
                                long pi64 = Convert.ToInt64(value);
                                propertys[j].SetValue(obj, pi64, null);
                            }
                            else if (str == "System.Byte")
                            {
                                byte pb = Convert.ToByte(value);
                                propertys[j].SetValue(obj, pb, null);
                            }
                            else
                            {
                                propertys[j].SetValue(obj, null, null);
                            }
                        }
                    }
                    list.Add(obj);
                }
            }
            return list;
        }

    }
View Code

如使用有問題,請留言。但願能幫到你~~~數據結構

相關文章
相關標籤/搜索