续【NPOI】导出Excel文件,后的导入Excel操作
关于【NPOI】的介绍和引用就不再说,上篇有讲到
将excel文件数据直接导入到数据,首先浏览器端要准备相对应格式的Excel文件才能正常的导入数据库。所以一般都有一个指定样式的Excel模板文件
实现方法:Ajax异步进行表单上传—>>一般处理程序–>>将文件保存到服务器—>>服务器读取文件–>>通过NPOI遍历Excel的内容–>>读取保存至数据库
一、Ajax异步提交表单
html代码:
1 2 3 4 5 6
| <form enctype="multipart/form-data" id="file-form"> <p> <a id="btnMCToOut" οnclick="importExcel()" class="easyui-linkbutton" data-options="iconCls:'icon_CloseAll'">导入Excel</a> <input type="file" name="filed" id="filed"> </p> </form>
|
注意:enctype=”multipart/form-data” id=”file-form”
JavaScript代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| // 导入Excel function importExcel() { var file = $("#filed").val(); if (file == null || file.length == 0) { DJMask.msg("请先选择上传文件!"); return false; } $('#file-form').ajaxSubmit({ type: 'POST', // HTTP请求方式 url: '../Ajax/Handler1.ashx', // 请求的URL地址 dataType: 'text', // 服务器返回数据转换成的类型 success: function (data) { DJMask.msg(data); }, error: function (data) { DJMask.msg("oh,似乎出现点问题了!"); } }); $('#dgMenCards').datagrid('reload', {});//刷新表格 }
|
注意引入js文件:
二、一般处理程序部分
1 2 3 4 5 6 7 8
| public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; HttpPostedFile filePost = context.Request.Files["filed"]; // 获取上传的文件 string filePath = SaveExcelFile(filePost); // 保存文件并获取文件路径 string msg= ExcelToDataTable(filePath, true); context.Response.Write(msg); }
|
主要分为两个方法
1.保存Excel文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| /// <summary> /// 保存Excel文件 /// <para>Excel的导入导出都会在服务器生成一个文件</para> /// <para>路径:UpFiles/ExcelFiles</para> /// </summary> /// <param name="file">传入的文件对象</param> /// <returns>如果保存成功则返回文件的位置;如果保存失败则返回空</returns> public static string SaveExcelFile(HttpPostedFile file) { try { var fileName = file.FileName.Insert(file.FileName.LastIndexOf('.'), "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff")); var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Upload"), fileName); string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } file.SaveAs(filePath); return filePath; } catch { return string.Empty; } }
|
2.读取Excel文件保存至数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| /// <summary> /// 上传读取文件 /// </summary> /// <param name="filePath"></param> /// <param name="isColumnName"></param> public string ExcelToDataTable(string filePath, bool isColumnName) { int count = 0; try {
DataTable dataTable = new DataTable(); FileStream fs = null; IWorkbook workbook = null; ISheet sheet = null; using (fs = new FileStream(filePath, FileMode.Open)) { if (filePath.IndexOf(".xlsx") > 0) { workbook = new XSSFWorkbook(fs); if (workbook != null) { sheet = workbook.GetSheetAt(0); if (sheet != null) { Models.MPMS_DBDataContext db = new Models.MPMS_DBDataContext(); int rowCount = sheet.LastRowNum; for (int i = 1; i <= rowCount; i++) { Models.MemCards model = new Models.MemCards(); IRow row = sheet.GetRow(i); model.CL_ID = int.Parse(row.GetCell(0).ToString()); model.S_ID = int.Parse(row.GetCell(1).ToString()); model.MC_CardID = (row.GetCell(2).ToString());//会员卡号
model.MC_Password = (row.GetCell(3).ToString());//卡片密码 model.MC_Name = (row.GetCell(4).ToString());//卡片密码 model.MC_Sex = int.Parse(row.GetCell(5).ToString());//会员性别
model.MC_Mobile = (row.GetCell(6).ToString());//手机号码 model.MC_Photo = "upload/1.jpg";//靓照
model.MC_Birthday_Month = 1;//会员生日--月 model.MC_Birthday_Day = 1;//会员生日--日 model.MC_BirthdayType = 1;//会员生日类型
model.MC_IsPast = 1;//是否设置卡片过期时间 model.MC_PastTime = DateTime.Now.AddYears(10);//卡片过期时间 model.MC_Point = int.Parse(row.GetCell(7).ToString());//当前积分 model.MC_Money = int.Parse(row.GetCell(8).ToString());//卡片付费 model.MC_TotalMoney = 0;//累计消费 model.MC_TotalCount = 0;//累计消费次数 model.MC_State = 1;//卡片状态 model.MC_IsPointAuto = 1;//积分是否可以自动换成等级
model.MC_RefererID = null;//推荐人ID model.MC_RefererCard = null;//推荐人卡号 model.MC_RefererName = null;//推荐人姓名
model.MC_CreateTime = DateTime.Now;//积分是否可以自动换成等级 count++; db.MemCards.InsertOnSubmit(model); db.SubmitChanges(); } } } } } } catch{ return "导入失败,字段错误!"; } return "成功导入" +count+ "条数据"; }
|
1 2 3 4 5
| /* 导入Excel时出现错误,错误提示:Wrong Local header signature: 0xE011CFD0,这个是excel的扩展名问题, .xlsx 应该XSSFWorkbook workbook = new XSSFWorkbook(file); 而xls应该用 HSSFWorkbook workbook = new HSSFWorkbook(file); */
|
上传的Excel模板:

上传后的结果: