.NET MVC上传一个文件,用NPOI解析后在界面上显示

上传一个Excel并解析,将解析结果存到DataTable中,然后再页面显示


1.  后台上传和解析代码

  public class ExcelController : Controller
    {
    
        public ActionResult ExcelUpload()
        {
            return View();
        }

        public ActionResult ExcelUploadSubmit(string excelTitle)
        {
            HttpPostedFileBase excelFile = Request.Files["excelFile"];     //取到上传域

            if (null != excelFile)
            {
                string fileName = Path.GetFileName(excelFile.FileName);           //取到文件的名称
                if(fileName.Equals("")||null == fileName){                        //没有选择文件就上传的话,则跳回到上传页面
                    return View("ExcelUpload");
                }
                string serverpath = Server.MapPath("/");
                excelFile.SaveAs(serverpath + @"\Upload\" + fileName);      //保存上传文件


                //parse the excel
                //save the excel content in the datatable
                DataTable dt = new DataTable();                                      

                dt.Columns.Add("Dept", Type.GetType("System.String"));
                dt.Columns.Add("FlowName", Type.GetType("System.String"));
                dt.Columns.Add("CurrUser", Type.GetType("System.String"));
                dt.Columns.Add("ApplyUser", Type.GetType("System.String"));        //新建一个DataTable,并指定列和列的类型

                FileStream inputStream = new FileStream(serverpath + @"\Upload\" + fileName, FileMode.Open);
                HSSFWorkbook workbook = new HSSFWorkbook(inputStream);          //解析上传的Excel

                HSSFSheet sheet = workbook.GetSheetAt(0) as HSSFSheet;
                int rowNum = sheet.PhysicalNumberOfRows;
                for (int i = 0; i < rowNum;i++ )
                {
                    HSSFRow row = sheet.GetRow(i) as HSSFRow;
                    int cellNum = row.PhysicalNumberOfCells;

                    DataRow newRow = dt.NewRow();                       //DataTable创建新行
                    for (int j = 0; j < cellNum;j++ )
                    {
                        HSSFCell cell = row.GetCell(j) as HSSFCell;
                        if (cell.CellType == CellType.Numeric)
                        {
                            newRow[j] = cell.NumericCellValue;               //给新建的行加列
                        }
                        else {
                            newRow[j] = cell.StringCellValue;
                        }
                      
                       
                    }
                    dt.Rows.Add(newRow);                   //新建的行加入到DataTable中

                }
                ViewData["excelTitle"] = excelTitle;
                ViewData["dt"] = dt;                        //存起来以便在前台显示

            }


            return View("ExcelUpload");
        }

    }

 


 2. 前台的页面ExcelUpload.aspx


    <form action="/Excel/ExcelUploadSubmit" method="post" enctype="multipart/form-data">
      <p> 
         Title: <input id="excelTitle" name="excelTitle" type="text" />
          </p>
          <p> 
         File: <input id="excelFile" name="excelFile" type="file" />
          </p>
          <p>
              <input id="Submit1" type="submit" value="submit"/></p>
      </form>


      <table id="dataTable">
      <tr>
      <td colspan="4" align="center">
      <%=ViewData["excelTitle"]%>
      </td>
      </tr>

      <%
         DataTable dt = (DataTable)ViewData["dt"];
          if(null != dt){
              for (int i = 0; i < dt.Rows.Count;i++ )
              {

 


              %>
             <tr>
            <td><%=dt.Rows[i]["Dept"]%></td>
             <td><%=dt.Rows[i]["FlowName"]%></td>
              <td><%=dt.Rows[i]["CurrUser"]%></td>
               <td><%=dt.Rows[i]["ApplyUser"]%></td>
             </tr>
              <%
              }
              %>

              <%
          }
           %>
           </table>

ASP.NET MVC 中使用 NPOI.NET平移版Apache POI库)处理CSV文件并将其数据添加到数据库的过程大致可以分为以下几个步骤: 1. HTML页面(前端): ```html <!-- 使用HTML5的File API --> <form action="UploadCsv" method="post" enctype="multipart/form-data"> <input type="file" id="csvFileInput" accept=".csv"> <button type="submit">上传</button> </form> <script> document.getElementById('csvFileInput').addEventListener('change', function (e) { var file = this.files[0]; // AJAX异步提交,这里省略Ajax代码,通常会用jQuery的$.ajax $.ajax({ url: '@Url.Action("UploadCsv", "YourControllerName")', data: new FormData(this), processData: false, contentType: false, type: 'POST', success: function (result) { console.log(result); }, error: function (error) { console.error(error); } }); }); </script> ``` 2. Controller(后端,假设在名为`YourControllerName`的控制器中): ```csharp using System; using System.Collections.Generic; using System.IO; using Microsoft.AspNetCore.Mvc; using NPOI; using NPOI.HSSF.usermodel; namespace YourNamespace.Controllers { public class YourControllerName : Controller { [HttpPost] public IActionResult UploadCsv(IFormFile csvFile) { if (csvFile == null || csvFile.Length <= 0) { return BadRequest("请选择文件"); } try { using (var stream = csvFile.OpenReadStream()) using (var reader = new HSSFWorkbook(stream)) { var sheet = reader.GetSheetAt(0); // 假设只有一个工作表 int rowCount = sheet.LastRowNum + 1; for (int i = 1; i <= rowCount; i++) { var row = sheet.getRow(i); // 获取并验证每一列的数据 string column1Value = row.Cells[0].GetStringCellValue(); string column2Value = row.Cells[1].GetStringCellValue(); // 添加到数据库A表中,这里省略实际的数据库操作,例如EF Core或Dapper // AddToDatabase(column1Value, column2Value); // 提供一些反馈,比如添加了某一行 Console.WriteLine($"已成功插入第{i}行:{column1Value}, {column2Value}"); } } return Ok("文件上传成功"); } catch (Exception ex) { return StatusCode((int)HttpStatusCode.BadRequest, ex.Message); } } private void AddToDatabase(string col1, string col2) { // 实现将数据添加到数据库的具体操作 // ... } } } ``` 注意,上述代码示例中,你需要先安装NPOI相关NuGet包,并处理异常、验证输入数据等实际情况。在数据库操作部分,需要替换为对应的ORM操作或直接使用ADO.NET
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sust2012

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值