ASP.NET MVC使用NPOI讀取excel數據


 一、下載引用

目前官網不能直接下載到引用的dll,需要自己打包(我沒有自己打包,我有現成的DLL,地址:https://files.cnblogs.com/files/dengxixi/NPOIdll.7z),即:NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,ICSharpCode.SharpZipLib.dll。(解壓密碼是:123456)

二、創建MVC項目,頁面代碼:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>使用NPOI導入excel</title>
    <script src="Scripts/jquery-1.8.2.min.js"></script>
    <style>
        .myFileUpload {
            position: absolute;
            display: block;
            width: 100px;
            height: 40px;
            opacity: 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <form class="form-horizontal" action="~/Home/Upload" role="form" method="post" enctype="multipart/form-data">
            <table style="margin:5px;height:70px;">
                <tr>
                    <td>請選擇文件:</td>
                    <td width="5px;"></td>
                    <td><input type="file" id="fileUpload" name="fileUpload"></td>
                    <td><input id="fileText" type="text" class="myFileUpload" disabled="disabled" /></td>
                    <td><button type="submit">上傳</button></td>
                </tr>
            </table>
        </form>
    </div>
</body>
</html>
View Code

三、EXCEL轉為為datatable類,網上百度的,改了下,因為沒有判斷excel的版本

    public class ExcelHelper
    {
        /// <summary>讀取excel 到datatable    
        /// 默認第一行為表頭,導入第一個工作表   
        /// </summary>      
        /// <param name="strFileName">excel文檔路徑</param>      
        /// <returns></returns>      
        public static DataTable ExcelToDataTable(string strFileName)
        {
            DataTable dt = new DataTable();
            FileStream file = null;
            IWorkbook Workbook = null;
            try
            {

                using (file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))//C#文件流讀取文件
                {
                    if (strFileName.IndexOf(".xlsx") > 0)
                        //把xlsx文件中的數據寫入Workbook中
                        Workbook = new XSSFWorkbook(file);

                    else if (strFileName.IndexOf(".xls") > 0)
                        //把xls文件中的數據寫入Workbook中
                        Workbook = new HSSFWorkbook(file);

                    if (Workbook != null)
                    {
                        ISheet sheet = Workbook.GetSheetAt(0);//讀取第一個sheet
                        System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
                        //得到Excel工作表的行 
                        IRow headerRow = sheet.GetRow(0);
                        //得到Excel工作表的總列數  
                        int cellCount = headerRow.LastCellNum;

                        for (int j = 0; j < cellCount; j++)
                        {
                            //得到Excel工作表指定行的單元格  
                            ICell cell = headerRow.GetCell(j);
                            dt.Columns.Add(cell.ToString());
                        }

                        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)
                                    dataRow[j] = row.GetCell(j).ToString();
                            }
                            dt.Rows.Add(dataRow);
                        }
                    }
                    return dt;
                }
            }

            catch (Exception)
            {
                if (file != null)
                {
                    file.Close();//關閉當前流並釋放資源
                }
                return null;
            }

        }
        /// <summary>   
        /// 從Excel中獲取數據到DataTable   
        /// </summary>   
        /// <param name="strFileName">Excel文件全路徑(服務器路徑)</param>   
        /// <param name="SheetName">要獲取數據的工作表名稱</param>   
        /// <param name="HeaderRowIndex">工作表標題行所在行號(從0開始)</param>   
        /// <returns></returns>   
        public static DataTable RenderDataTableFromExcel(string strFileName, string SheetName, int HeaderRowIndex)
        {
            IWorkbook Workbook = null;

            using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
            {
                if (strFileName.IndexOf(".xlsx") > 0)

                    Workbook = new XSSFWorkbook(file);

                else if (strFileName.IndexOf(".xls") > 0)

                    Workbook = new HSSFWorkbook(file);
                ISheet sheet = Workbook.GetSheet(SheetName);
                return RenderDataTableFromExcel(Workbook, SheetName, HeaderRowIndex);
            }
        }

        /// <summary>   
        /// 從Excel中獲取數據到DataTable   
        /// </summary>   
        /// <param name="workbook">要處理的工作薄</param>   
        /// <param name="SheetName">要獲取數據的工作表名稱</param>   
        /// <param name="HeaderRowIndex">工作表標題行所在行號(從0開始)</param>   
        /// <returns></returns>   
        public static DataTable RenderDataTableFromExcel(IWorkbook workbook, string SheetName, int HeaderRowIndex)
        {
            ISheet sheet = workbook.GetSheet(SheetName);
            DataTable table = new DataTable();
            try
            {
                IRow headerRow = sheet.GetRow(HeaderRowIndex);
                int cellCount = headerRow.LastCellNum;

                for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                {
                    DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                    table.Columns.Add(column);
                }

                int rowCount = sheet.LastRowNum;

                #region 循環各行各列,寫入數據到DataTable
                for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    DataRow dataRow = table.NewRow();
                    for (int j = row.FirstCellNum; j < cellCount; j++)
                    {
                        ICell cell = row.GetCell(j);
                        if (cell == null)
                        {
                            dataRow[j] = null;
                        }
                        else
                        {
                            //dataRow[j] = cell.ToString();   
                            switch (cell.CellType)
                            {
                                case CellType.Blank:
                                    dataRow[j] = null;
                                    break;
                                case CellType.Boolean:
                                    dataRow[j] = cell.BooleanCellValue;
                                    break;
                                case CellType.Numeric:
                                    dataRow[j] = cell.ToString();
                                    break;
                                case CellType.String:
                                    dataRow[j] = cell.StringCellValue;
                                    break;
                                case CellType.Error:
                                    dataRow[j] = cell.ErrorCellValue;
                                    break;
                                case CellType.Formula:
                                default:
                                    dataRow[j] = "=" + cell.CellFormula;
                                    break;
                            }
                        }
                    }
                    table.Rows.Add(dataRow);
                    //dataRow[j] = row.GetCell(j).ToString();   
                }
                #endregion
            }
            catch (System.Exception ex)
            {
                table.Clear();
                table.Columns.Clear();
                table.Columns.Add("出錯了");
                DataRow dr = table.NewRow();
                dr[0] = ex.Message;
                table.Rows.Add(dr);
                return table;
            }
            finally
            {
                //sheet.Dispose();   
                workbook = null;
                sheet = null;
            }
            #region 清除最后的空行
            for (int i = table.Rows.Count - 1; i > 0; i--)
            {
                bool isnull = true;
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    if (table.Rows[i][j] != null)
                    {
                        if (table.Rows[i][j].ToString() != "")
                        {
                            isnull = false;
                            break;
                        }
                    }
                }
                if (isnull)
                {
                    table.Rows[i].Delete();
                }
            }
            #endregion
            return table;
        }
   
    }
View Code

四、調用方法

    public string Upload(HttpPostedFileBase fileUpload)
        {
            if (fileUpload == null)
            {
                return "文件為空";
            }
            try
            {
                //將硬盤路徑轉化為服務器路徑的文件流
                string fileName = Path.Combine(Request.MapPath("~/SaveFile"), Path.GetFileName(fileUpload.FileName));
                //NPOI得到EXCEL的第一種方法              
                fileUpload.SaveAs(fileName);
                DataTable dtData = ExcelHelper.ExcelToDataTable(fileName);
                //得到EXCEL的第二種方法(第一個參數是文件流,第二個是excel標簽名,第三個是第幾行開始讀0算第一行)
                DataTable dtData2 = ExcelHelper.RenderDataTableFromExcel(fileName, fileUpload.FileName, 0);
                return "導入成功";
            }
            catch
            {
                return "導入失敗";
            }
        }

 

五、調試截圖及excel 數據截圖:

以上就是把excel轉化為datatable的方法。轉化為datatable之后就可以進行插入數據庫或者顯示到頁面了。

 


免責聲明!

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



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