隐藏

Asp.Net Core 使用NPOI 读取EXCEL

发布:2023/3/24 22:02:06作者:管理员 来源:本站 浏览次数:395

1.添加依赖 DotNetCore.NPOI




2.读取Excel类库


   using System;

   using System.Collections.Generic;

   using System.Linq;

   using System.Threading.Tasks;

   

   using System.IO;

   using System.Reflection;

   using System.Collections;

   using System.Data;

   using NPOI.SS.UserModel;

   

   namespace SVW_ReOnLine.BLL.Common

   {

       /// <summary>

       /// Summary description for OfficeHelper

       /// </summary>

       public class OfficeHelper

       {

           /// <summary>

           /// 将excel文件内容读取到DataTable数据表中

           /// </summary>

           /// <param name="fileName">文件完整路径名</param>

           /// <param name="sheetName">指定读取excel工作薄sheet的名称</param>

           /// <param name="isFirstRowColumn">第一行是否是DataTable的列名:true=是,false=否</param>

           /// <returns>DataTable数据表</returns>

           public static DataTable ReadExcelToDataTable(string fileName, string sheetName = null, bool isFirstRowColumn = true)

           {

               //定义要返回的datatable对象

               DataTable data = new DataTable();

               //excel工作表

               ISheet sheet = null;

               //数据开始行(排除标题行)

               int startRow = 0;

               try

               {

                   if (!File.Exists(fileName))

                   {

                       return null;

                   }

                   //根据指定路径读取文件

                   FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

                   //根据文件流创建excel数据结构

                   IWorkbook workbook = WorkbookFactory.Create(fs);

                   //IWorkbook workbook = new HSSFWorkbook(fs);

                   //如果有指定工作表名称

                   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);

                   }

                   if (sheet != null)

                   {

                       IRow firstRow = sheet.GetRow(0);

                       //一行最后一个cell的编号 即总的列数

                       int cellCount = firstRow.LastCellNum;

                       //如果第一行是标题列名

                       if (isFirstRowColumn)

                       {

                           for (int i = firstRow.FirstCellNum; i < cellCount; ++i)

                           {

                               ICell 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

                       {

                           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;

               }

               catch (Exception ex)

               {

                   throw ex;

               }

           }

   

           /// <summary>

           /// 将文件流读取到DataTable数据表中

           /// </summary>

           /// <param name="fileStream">文件流</param>

           /// <param name="sheetName">指定读取excel工作薄sheet的名称</param>

           /// <param name="isFirstRowColumn">第一行是否是DataTable的列名:true=是,false=否</param>

           /// <returns>DataTable数据表</returns>

           public static DataTable ReadStreamToDataTable(Stream fileStream, string sheetName = null, bool isFirstRowColumn = true)

           {

               //定义要返回的datatable对象

               DataTable data = new DataTable();

               //excel工作表

               ISheet sheet = null;

               //数据开始行(排除标题行)

               int startRow = 0;

               try

               {

                   //根据文件流创建excel数据结构,NPOI的工厂类WorkbookFactory会自动识别excel版本,创建出不同的excel数据结构

                   IWorkbook workbook = WorkbookFactory.Create(fileStream);

                   //如果有指定工作表名称

                   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);

                   }

                   if (sheet != null)

                   {

                       IRow firstRow = sheet.GetRow(0);

                       //一行最后一个cell的编号 即总的列数

                       int cellCount = firstRow.LastCellNum;

                       //如果第一行是标题列名

                       if (isFirstRowColumn)

                       {

                           for (int i = firstRow.FirstCellNum; i < cellCount; ++i)

                           {

                               ICell 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

                       {

                           startRow = sheet.FirstRowNum;

                       }

                       //最后一列的标号

                       int rowCount = sheet.LastRowNum;

                       for (int i = startRow; i <= rowCount; ++i)

                       {

                           IRow row = sheet.GetRow(i);

                           if (row == null || row.FirstCellNum < 0) continue; //没有数据的行默认是null

   

                           DataRow dataRow = data.NewRow();

                           for (int j = row.FirstCellNum; j < cellCount; ++j)

                           {

                               //同理,没有数据的单元格都默认是null

                               ICell cell = row.GetCell(j);

                               if (cell != null)

                               {

                                   if (cell.CellType == CellType.Numeric)

                                   {

                                       //判断是否日期类型

                                       if (DateUtil.IsCellDateFormatted(cell))

                                       {

                                           dataRow[j] = row.GetCell(j).DateCellValue;

                                       }

                                       else

                                       {

                                           dataRow[j] = row.GetCell(j).ToString().Trim();

                                       }

                                   }

                                   else

                                   {

                                       dataRow[j] = row.GetCell(j).ToString().Trim();

                                   }

                               }

                           }

                           data.Rows.Add(dataRow);

                       }

                   }

                   return data;

               }

               catch (Exception ex)

               {

                   throw ex;

               }

           }

       }

   }



3.控制器端Controller


   public class UploadController : Controller

       {

           private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(UploadController));

           private IHostingEnvironment hostingEnv;

           public UploadController(IHostingEnvironment env)

           {

               this.hostingEnv = env;

           }

           [HttpPost]

           public JsonResult UploadFilesAjax()

           {

               JArray lst = new JArray();

               JObject jsonResult = new JObject();

               int result = 0;

               //long size = 0;

               string fileNamePath = string.Empty;

               string RequestPath = string.Empty;

               try

               {

                   //string domurl = @"http://dy.dt1.biz/upload/";

                   string domurl = @"http://localhost:57663/upload/";

                   var files = Request.Form.Files;

                   foreach (var file in files)

                   {

                       string fileName = DateTime.Now.ToString("MMddHHmmss") + file.FileName;

                       fileNamePath = Path.Combine("upload", fileName);

                       string serverUrl = Request.HttpContext.Connection.LocalIpAddress.ToStringExt() + ":" + Request.HttpContext.Connection.LocalPort.ToStringExt() + @"/upload/DeviceImage.jpg";

                       log.Info("客户端IP地址2:" + serverUrl);

                       RequestPath = domurl + fileName;

                       //size += file.Length;

   

                       //保存文件

                       //物理路径

                       string SavePath=Path.Combine(hostingEnv.WebRootPath, fileNamePath);

                       using (FileStream fs = new FileStream(SavePath, FileMode.CreateNew))

                       {

                           file.CopyTo(fs);

                           fs.Flush();

                           result = 1;

                       }

                     

                       DataTable dt=  OfficeHelper.ReadExcelToDataTable(SavePath);

                       for (int i = 0; i < dt.Rows.Count; i++)

                       {

                           JObject obj = new JObject();

                           for (int j = 0; j < dt.Columns.Count; j++)

                           {

                             

                               obj.Add("col"+j.ToString(), dt.Rows[i][j].ToStringExt());

                             

                           }

                           lst.Add(obj);

                       }

                     

   

                   }

                   //string url = Request.HttpContext.Connection.RemoteIpAddress.ToStringExt()+":"+ Request.HttpContext.Connection.RemotePort.ToStringExt();

                   jsonResult.Add("Result", result);

                   jsonResult.Add("ImageUrl", RequestPath);

                   jsonResult.Add("Data", lst);

               }

               catch (Exception ex)

               {

                   log.Error("上传文件错误信息列表错误:" + ex.ToStringExt());

                   jsonResult.Add("Result", result);

               }

               return Json(jsonResult);

           }


4. index.html


   <!DOCTYPE html>

   <html>

   

   <head>

       <meta charset="utf-8">

       <meta http-equiv="X-UA-Compatible" content="IE=edge">

       <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

       <title>用户登陆</title>

       <link href="/css/bootstrap.min.css" rel="stylesheet">

       <style>

           .panel {

               width: 375px;

               margin: 15px auto;

           }

   

           #submit {

               width: 100%;

           }

   

           img {

               width: 100%;

           }

   

           .breadcrumb {

               margin-bottom: 10px;

           }

   

           @media screen and (max-width: 480px) {

               .panel {

                   width: 100%;

                   margin: 0;

                   border: 0;

                   box-shadow: none;

               }

           }

       </style>

   </head>

   

   <body>

       <div class="panel panel-default">

           <div class="panel-heading" align="center"><b>用户登陆</b></div>

           <div class="panel-body">

               

                   <input type="file" id="files" name="files" multiple />

                   <input type="button" id="uploadExcel" value="Upload Selected Files" />

               

           </div>

       </div>

       <script src="/js/jquery.min.js"></script>

       <script src="/js/bootstrap.min.js"></script>

   

       <script>

       

           $("#uploadExcel").click(function (evt) {

               var fileUpload = $("#files").get(0);

               var files = fileUpload.files;

               var data = new FormData();

               for (var i = 0; i < files.length; i++) {

                   data.append(files[i].name, files[i]);

               }

               $.ajax({

                   type: "POST",

                   url: "api/Upload/UploadFilesAjax",

                   contentType: false,

                   processData: false,

                   data: data,

                   success: function (message) {

                       //var Msg = eval('(' + message + ')');

   

                       alert("【Result】:" + message.Result + ";【ImageUrl】:" + message.ImageUrl);

                       1

                   },

                   error: function () {

                       alert("There was error uploading files!");

                   }

               });

           });

       </script>

   

   

   </body>

   

   </html>