• .NET MVC+angular导入导出


    cshtml:

    1 <form class="form-horizontal" id="form1" role="form" ng-submit="import ()" enctype="multipart/form-data">
    2   <button class="btn btn-primary" type="button" ng-click="downloadTemp()">下载模板</button>
    3   <button type="submit" class="btn btn-primary">导入</button>
    4 </form>

    js:

     1 //下载模板
     2 $scope.downloadTemp = function () {
     3   downloadfile({
     4     url: "/Temp/DownloadTemp"
     5   });
     6 }
     7 
     8 
     9 
    10 //导入
    11 $scope.import = function () {
    12   var url = "/Temp/Import";
    13   var formData = new FormData();//使用FormData进行文件上传
    14   formData.append("file", file.files[0]);//拿到当前文件
    15   $http.post(url, formData, {
    16     transformRequest: angular.identity,
    17     headers: { 'Content-Type': undefined }
    18   }).success(function (data, status) {
    19     var success = "";
    20     if (data.success = false)
    21     {
    22       success = "导入失败!";
    23     }
    24     $scope.AlertMesage(success + data.Message, 1);
    25   }).error(function (data, status) {
    26     $scope.AlertMesage("导入异常:[" + data.Message + "]!", 3);
    27   });
    28 };

    Controller:

     1 /// <summary>
     2 /// 模板下载
     3 /// </summary>
     4 /// <returns></returns>
     5 [HttpPost]
     6 public FileResult DownloadTemp()
     7 {
     8   try
     9   {
    10     var fileName = $"数据_{DateTime.Now:yyyyMMdd}.xls";
    11     //创建Excel文件的对象
    12     HSSFWorkbook book = new HSSFWorkbook();
    13     //添加一个sheet
    14     ISheet sheet1 = book.CreateSheet("Sheet1");
    15     #region 给sheet1添加第一行的头部标题
    16     IRow row1 = sheet1.CreateRow(0);
    17     //给sheet1添加第一行的头部标题
    18     row1.CreateCell(0).SetCellValue("编号");
    19     row1.CreateCell(1).SetCellValue("名称");
    20     row1.CreateCell(2).SetCellValue("运能");
    21     #endregion
    22     //获取正常状态(自营,在用,有效)的站点运能数据
    23     var list = GetAllListInfo();
    24     if (list != null && list .Any())
    25     {
    26       for (int i = 0; i < list.Count(); i++)
    27       {
    28         NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
    29         rowtemp.CreateCell(0).SetCellValue(capacityList[i].Code);
    30         rowtemp.CreateCell(1).SetCellValue(capacityList[i].Name);
    31         rowtemp.CreateCell(2).SetCellValue(capacityList[i].Capacity);
    32 
    33       }
    34     }
    35     // 写入到客户端 
    36     MemoryStream ms = new MemoryStream();
    37     book.Write(ms);
    38     ms.Seek(0, SeekOrigin.Begin);
    39     return File(ms, "application/vnd.ms-excel", fileName);
    40   }
    41   catch (Exception ex)
    42   {
    43     throw new Exception("导出数据失败:" + ex.ToString());
    44   }
    45 }
      1         /// <summary>
      2         /// 导入
      3         /// </summary>
      4         /// <returns></returns>
      5         [HttpPost]
      6         public JsonResult Import()
      7         {
      8             try
      9             {
     10                 //接收客户端传递过来的数据
     11                 HttpPostedFileBase file = Request.Files["file"];
     12                 if (file == null)
     13                 {
     14                     return Json(new
     15                     {
     16                         Success = false,
     17                         Message = "请选择上传的Excel文件",
     18                     });
     19                 }
     20                 //对文件的格式判断,此处省略
     21                 string fileExt = Path.GetExtension(file.FileName.Replace(""", ""));
     22                 var supportArr = new string[] { ".xls", ".xlsx" };
     23                 if (supportArr.Contains(fileExt) == false)
     24                 {
     25                     //throw new ArgumentException(string.Format("不支持的文件类型:{0}", fileExt));
     26                     return Json(new
     27                     {
     28                         Success = false,
     29                         Message = string.Format("不支持的文件类型:{0}", fileExt),
     30                     });
     31                 }
     32 
     33                 Stream inputStream = file.InputStream;
     34                 //HSSFWorkbook hssfworkbook = new HSSFWorkbook(inputStream);
     35                 IWorkbook workbook = null;
     36                 if (fileExt == ".xlsx")
     37                 {
     38                     workbook = new XSSFWorkbook(inputStream); // .xlsx
     39                 }
     40                 else
     41                 {
     42                     workbook = new HSSFWorkbook(inputStream); // .xls
     43                 }
     44                 NPOI.SS.UserModel.ISheet sheet = workbook.GetSheetAt(0);
     45                 // IRow headerRow = sheet.GetRow(0);//第一行为标题行
     46                 // int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
     47                 int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
     48                 List<StationEntity> list = new List<StationEntity>();
     49                 if (rowCount > 0)
     50                 {
     51                     try
     52                     {
     53                          54                         for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
     55                         {
     56                             IRow row = sheet.GetRow(i);
     57                             StationEntity model = new StationEntity();
     58 
     59                             if (row != null)
     60                             {
     61                                
     62                                 model.Code = row.GetCell(0) != null ? GetCellValue(row.GetCell(0)) : string.Empty ;
     63                                 model.Name = row.GetCell(1) != null ? GetCellValue(row.GetCell(1)) : string.Empty;
     64                                 model.Capacity = row.GetCell(2) != null ? ConvertHelper.ToInt32(GetCellValue(row.GetCell(2))) : 0;
     65                                 list.Add(model);
     66                             }
     67                         }
     68                     }
     69                     catch (Exception)
     70                     {
     71                         return Json(new
     72                         {
     73                             Success = false,
     74                             Message = "请填写正确格式的数据",
     75                         });
     76                     }
     77                 }
     78 
     79                 //导入运能数据
     80                 if (list != null && list.Any())
     81                 {
     82                     string msg = string.Empty;
     83                     var success = StationBLL.RefreshData(list,out msg);
     84                     return Json(new
     85                     {
     86                         Success = success,
     87                         Message = msg,
     88                     });
     89                 }
     90                 else
     91                     return Json(new
     92                     {
     93                         Success = false,
     94                         Message = "没有要导入的数据",
     95                     });
     96             }
     97             catch (Exception ex)
     98             { 99                 throw new Exception("导入数据失败:" + ex.ToString());
    100             }
    101         }
     1         /// 根据Excel列类型获取列的值
     2         /// </summary>
     3         /// <param name="cell">Excel列</param>
     4         /// <returns></returns>
     5         private static string GetCellValue(ICell cell)
     6         {
     7             if (cell == null)
     8                 return string.Empty;
     9             switch (cell.CellType)
    10             {
    11                 case CellType.Blank:
    12                     return string.Empty;
    13                 case CellType.Boolean:
    14                     return cell.BooleanCellValue.ToString();
    15                 case CellType.Error:
    16                     return cell.ErrorCellValue.ToString();
    17                 case CellType.Numeric:
    18                 case CellType.Unknown:
    19                 default:
    20                     return cell.ToString();
    21                 case CellType.String:
    22                     return cell.StringCellValue;
    23                 case CellType.Formula:
    24                     try
    25                     {
    26                         HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
    27                         e.EvaluateInCell(cell);
    28                         return cell.ToString();
    29                     }
    30                     catch
    31                     {
    32                         return cell.NumericCellValue.ToString();
    33                     }
    34             }
    35         }
  • 相关阅读:
    深度学习大牛Yoshua Bengio
    mysql select简单用法
    CF 191 div2
    MySQL 讨厌哪种类型的查询
    Python 中的list小结
    定时器常用的两种工作方式及编程要点
    Linux下which、whereis、locate、find 区别
    Dalvik虚拟机的优化机制
    [leetcode]Partition List
    tomcat:Could not publish to the server. java.lang.IndexOutOfBoundsException
  • 原文地址:https://www.cnblogs.com/chocolatexll/p/10436799.html
Copyright © 2020-2023  润新知