Mvc导入导出Excel

Posted 成败在我手

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mvc导入导出Excel相关的知识,希望对你有一定的参考价值。

在项目中添加对NPOI的引用

视图部分如下:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

@Html.ActionLink("导出用户", "ExportExcel")
<br />
@using (@Html.BeginForm("ImportExcel", "Excel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <text>选择上传Excel文件:</text>
    <input name="file" type="file" id="file" />
    <input type="submit" name="Upload" value="批量导入用户" />

  控制器部分:

public class ExcelController : Controller
    {
        //
        // GET: /Excel/

        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 批量导出Excel
        /// </summary>
        /// <returns></returns>
        public FileResult ExportExcel()
        {
            //创建Excel文件的对象
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
            //获取list数据
            WinDataEntities db = new WinDataEntities();//EF上下文对象
            List<UserInfo> list = db.UserInfo.Where<UserInfo>(u => true).ToList();
            //给sheet1添加第一行的头部标题
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("姓名");
            row1.CreateCell(1).SetCellValue("登录名");
            //将数据逐步写入sheet1各个行
            for (int i = 0; i < list.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(list[i].TrueName);
                rowtemp.CreateCell(1).SetCellValue(list[i].UserName);
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", "用户.xls");
        }
        /// <summary>
        /// 批量导入Excel
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportExcel()
        {
            try
            {

            HttpPostedFileBase file = Request.Files["file"];//接收客户端传递过来的数据.
                if(file==null)
                {
                    return Content("请选择上传的Excel文件");
                }
                else
                {
                    //对文件的格式判断,此处省略
                    WinDataEntities db = new WinDataEntities();//EF上下文对象
                    Stream inputStream = file.InputStream;
                    HSSFWorkbook hssfworkbook = new HSSFWorkbook(inputStream);
                    NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
                    // IRow headerRow = sheet.GetRow(0);//第一行为标题行
                    // int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
                    int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1

                    for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        NewUser model = new NewUser();

                        if (row != null)
                        {
                            if (row.GetCell(0) != null)
                            {
                                model.TrueName = GetCellValue(row.GetCell(0));
                            }
                            if (row.GetCell(1) != null)
                            {
                                model.LoginName = GetCellValue(row.GetCell(1));
                            }

                        }

                        db.NewUser.Add(model);
                    }
                    db.SaveChanges();
                    return Content("导入成功");
                }

            }
            catch (Exception)
            {

                return Content("导入失败");
            }
            

        }
        /// <summary>
        /// 根据Excel列类型获取列的值
        /// </summary>
        /// <param name="cell">Excel列</param>
        /// <returns></returns>
        private static string GetCellValue(ICell cell)
        {
            if (cell == null)
                return string.Empty;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return string.Empty;
                case CellType.Boolean:
                    return cell.BooleanCellValue.ToString();
                case CellType.Error:
                    return cell.ErrorCellValue.ToString();
                case CellType.Numeric:
                case CellType.Unknown:
                default:
                    return cell.ToString();//This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Formula:
                    try
                    {
                        HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                        e.EvaluateInCell(cell);
                        return cell.ToString();
                    }
                    catch
                    {
                        return cell.NumericCellValue.ToString();
                    }
            }
        }

    }

  

以上是关于Mvc导入导出Excel的主要内容,如果未能解决你的问题,请参考以下文章

Mvc导入导出Excel

在mvc4中上传导入和导出excel表方法总结

构建ASP.NET MVC5+EF6+EasyUI 1.4.3+Unity4.x注入的后台管理系统(63)-Excel导入和导出

MVC 导出EXCEL

构建ASP.NET MVC5+EF6+EasyUI 1.4.3+Unity4.x注入的后台管理系统(63)-Excel导入和导出

求springmvc导入导出Excel的例子,越全面越好。