C#使用NOPI導入Excel


使用NOPI導入Excel文檔

NOPI版本:2.3.0,依賴於NPOI的SharpZipLib版本:0.86,經測試適用於.net4.0+

記錄遇到的幾個問題

  1. NOPI中的IWorkbook接口:xls使用HSSFWorkbook類實現,xlsx使用XSSFWorkbook類實現
  2. 日期轉換,判斷row.GetCell(j).CellType == NPOI.SS.UserModel.CellType.Numeric && HSSFDateUtil.IsCellDateFormatted(row.GetCell(j)
    不能直接使用row.GetCell(j).DateCellValue,這玩意會直接拋出異常來~

1. 將文件流轉換為DataTable

    /// <summary>
    /// 根據Excel格式讀取Excel
    /// </summary>
    /// <param name="stream">文件流</param>
    /// <param name="type">Excel格式枚舉類型,xls/xlsx</param>
    /// <param name="sheetName">表名,默認取第一張</param>
    /// <returns>DataTable</returns>
    private static DataTable ImportExcel(Stream stream, ExcelExtType type, string sheetName)
    {
        DataTable dt = new DataTable();
        IWorkbook workbook;
        try
        {
            //xls使用HSSFWorkbook類實現,xlsx使用XSSFWorkbook類實現
            switch (type)
            {
                case ExcelExtType.xlsx:
                    workbook = new XSSFWorkbook(stream);
                    break;
                default:
                    workbook = new HSSFWorkbook(stream);
                    break;
            }
            ISheet sheet = null;
            //獲取工作表 默認取第一張
            if (string.IsNullOrWhiteSpace(sheetName))
                sheet = workbook.GetSheetAt(0);
            else
                sheet = workbook.GetSheet(sheetName);

            if (sheet == null)
                return null;
            IEnumerator rows = sheet.GetRowEnumerator();
            #region 獲取表頭
            IRow headerRow = sheet.GetRow(0);
            int cellCount = headerRow.LastCellNum;
            for (int j = 0; j < cellCount; j++)
            {
                ICell cell = headerRow.GetCell(j);
                if (cell != null)
                {
                    dt.Columns.Add(cell.ToString());
                }
                else
                {
                    dt.Columns.Add("");
                }
            }
            #endregion
            #region 獲取內容
            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                DataRow dataRow = dt.NewRow();

                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                    {
                        //判斷單元格是否為日期格式
                        if (row.GetCell(j).CellType == NPOI.SS.UserModel.CellType.Numeric && HSSFDateUtil.IsCellDateFormatted(row.GetCell(j)))
                        {
                            if (row.GetCell(j).DateCellValue.Year >=1970)
                            {
                                dataRow[j] = row.GetCell(j).DateCellValue.ToString();
                            }
                            else
                            {
                                dataRow[j] = row.GetCell(j).ToString();

                            }
                        }
                        else
                        {
                            dataRow[j] = row.GetCell(j).ToString();
                        }
                    }
                }
                dt.Rows.Add(dataRow);
            }
            #endregion

        }
        catch (Exception ex)
        {
            dt=null;
        }
        finally
        {
            //if (stream != null)
            //{
            //    stream.Close();
            //    stream.Dispose();
            //}
        }
        return dt;
    }

2. 文件上載導入

    /// <summary>
    /// 上傳Excel導入
    /// </summary>
    /// <param name="file">上載文件對象</param>
    /// <param name="errorMsg">錯誤信息</param>
    /// <param name="sheetName">表名,默認取第一張</param>
    /// <returns></returns>
    public static DataTable Import(System.Web.HttpPostedFileBase file, ref string errorMsg, string sheetName = "")
    {
        if (file == null || file.InputStream == null || file.InputStream.Length == 0)
        {
            errorMsg = "請選擇要導入的Excel文件";
            return null;
        }
        var excelType = GetExcelFileType(file.FileName);
        if (excelType == null)
        {
            errorMsg = "請選擇正確的Excel文件";
            return null;
        }
        using (var stream = new MemoryStream())
        {
            file.InputStream.Position = 0;
            file.InputStream.CopyTo(stream);
            var dt = ImportExcel(stream, excelType.Value, sheetName);
            if (dt == null)
                errorMsg = "導入失敗,請選擇正確的Excel文件";
            return dt;
        }
    }

3. 本地路徑讀取導入

    /// <summary>
    /// 根據文件路徑導入Excel
    /// </summary>
    /// <param name="filePath"></param>
    /// <param name="errorMsg">錯誤信息</param>
    /// <param name="sheetName">表名,默認取第一張</param>
    /// <returns>可能為null的DataTable</returns>
    public static DataTable Import(string filePath, ref string errorMsg, string sheetName = "")
    {
        var excelType = GetExcelFileType(filePath);
        if (GetExcelFileType(filePath) == null)
        {
            errorMsg = "請選擇正確的Excel文件";
            return null;
        }
        if (!File.Exists(filePath))
        {
            errorMsg = "沒有找到要導入的Excel文件";
            return null;
        }
        DataTable dt;
        using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            dt = ImportExcel(stream, excelType.Value, sheetName);
        }
        if (dt == null)
            errorMsg = "導入失敗,請選擇正確的Excel文件";
        return dt;
    }

4.完整demo

附贈一個winform導入Excel的Demo。
https://github.com/yimogit/NopiExcelDemo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM