一、EXCEL 导入(Excel 导入导出实际项目中会被封装成**Helper 本示例只对简单功能做演示)
NPOI 包引用
视图view
@{ ViewBag.Title = "NPOIExcel"; } <h2>NPOIExcel</h2> <form action="@Url.Action("NPOIInport", "Home")" method="post" enctype="multipart/form-data"> <input type="file" name="Importexcelfile" /> <button type="submit">提交</button> </form> //enctype="multipart/form-data" 上传文件时form 表单必加
Action
命名空间引用
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
/// <summary> /// NPOI 导入excel /// </summary> /// <returns></returns> [HttpPost] public ActionResult NPOIInport() { bool isok = false; string msg = string.Empty; var file = Request.Files["Importexcelfile"];//接收的文件对象 var filename = SaveUploadExcel(file);//将文件保存至某一路径下 并形成新的文件名称 var filePath=System.Configuration.ConfigurationManager.AppSettings["Upload"] + @"excel" + filename;//新路径 IWorkbook workbook = null; //定义工作簿接口 ISheet sheet=null;//定义sheet表 DataTable data = new DataTable(); FileStream filestream = new FileStream(filePath, FileMode.Open, FileAccess.Read); if (file.ContentLength>0) { if (filePath.IndexOf(".xlsx") > 0) { workbook = new XSSFWorkbook(filestream);//.xlsx 文件 } else { workbook = new HSSFWorkbook(filestream);//.xls文件 } sheet = workbook.GetSheetAt(0);//默认第一个sheet sheet 下标 //sheet = workbook.GetSheet("sheet的名字");//获取想要查询sheet的名字 if (sheet!=null) { for (int i = 0; i < sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i);//获取第一行 一般都是表头 var firstvalue = row.GetCell(0);//第一行的第一列 var secondvalue = row.GetCell(1); } //常见读取excel 已经够用 实际项目中会遇到 再次封装数据形成table 一般这个帮助类会叫**Helper IRow firstrow = sheet.GetRow(0); int cellcount = firstrow.LastCellNum;//总列数 for (int i = firstrow.FirstCellNum; i < cellcount; i++) { ICell icell = firstrow.GetCell(i); if (icell!=null) { string cellvalue = icell.StringCellValue;//获取当前单元格的value DataColumn column = new DataColumn(cellvalue); data.Columns.Add(column);//添加表头 } } int startrow = sheet.FirstRowNum + 1; for (int i = startrow; i < sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); if (row!=null) { DataRow datarow = data.NewRow(); for (int j = row.FirstCellNum; j < cellcount; j++) { if (row.GetCell(j)!=null) { datarow[j] = row.GetCell(j).ToString(); } } data.Rows.Add(datarow); } } //return data; } } return Json(new { Isok = isok, Msg = msg }); } public static string SaveUploadExcel(HttpPostedFileBase fileexcel) { string filename = fileexcel.FileName; string extension = Path.GetExtension(filename); int filesize = fileexcel.ContentLength; if (filesize>int.Parse(System.Configuration.ConfigurationManager.AppSettings["UploadFileSize"])) { return "文件超过上限"; } string dirPath = System.Configuration.ConfigurationManager.AppSettings["Upload"] + @"excel"; //生成新的文件名 string newFileName = string.Format("{0}{1}", DateTime.Now.ToString("yyMMddHHmmssfffffff"), extension); if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); fileexcel.SaveAs(dirPath + newFileName); //返回新生成的文件名称 return newFileName; }
二、EXCEL 导出