一、view视图 <a class="mini-button" iconcls="icon-upload" onclick="uploadExcel()">导入</a> <a class="mini-button" iconcls="icon-download" onclick="exportModel">导出模板</a> @* 导入功能 *@ <div id="win3" class="mini-window" title="Window"style="width:300px;height:200px;"showmodal="true"> <div id="repeat"></div> <div id="repeat2"> <a href="javascript:$('#file_upload').uploadify('upload', '*')">上传</a> <a href="#">|</a> <a href="javascript:toDB()">导入</a> </div> </div> 二、javaScript (导入) //弹出框 function uploadExcel() { win3.setTitle("请选择上传文件"); win3.show(); $("#repeat").empty(); $("#repeat").append("<input type='file' id='file_upload' />"); $("#repeat2").hide(); initSendFile(); } //初始化上传控件 function initSendFile() { $("#file_upload").uploadify({ 'swf': '../../Scripts/uploadify-v3.1/uploadify.swf', 'uploader': '/Equipment/Upload', buttonText: '请选择上传文件', fileTypeExts: '*.xls;*.xlsx;', auto: false, multi: false, uploadLimit: 1, 'onUploadSuccess': function (file, data, response) { if (response == true) { mini.alert("上传成功"); } }, 'removeCompleted': false, 'onDialogClose': function (queueData) { if (queueData.filesQueued !='0') { $("#repeat2").show(); } }, 'onCancel': function (file) { $("#repeat2").hide(); } }); } //导入文件到数据库 function toDB() { $.ajax({ type: 'post', async: false, url: '/Equipment/toDB', success: function (result) { mini.alert("导入成功"); win3.hide(); dg.reload(); tree.reload(); }, error: function () { mini.alert("导入失败!"); } }); } (导出) //导出模板 function exportModel() { filePath = "Uploads/ModelFile/机泵台账模版.xlsx"; fileName = "机泵台账模板.xlsx"; window.location = "/Equipment/DownFile?filePath=" + filePath + "&fileName=" + fileName; } 三、Controller /// <summary> /// 上传文件到服务器 /// </summary> /// <param name="fileData"></param> /// <returns></returns> public JsonResult Upload(HttpPostedFileBase fileData){ if (fileData != null) { try { // 文件上传后的保存路径 string filePath = Server.MapPath("~/Uploads/UploadExcel/"); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string fileName = Path.GetFileName(fileData.FileName);// 原始文件名称 string fileExtension = Path.GetExtension(fileName); // 文件扩展名 string saveName = Guid.NewGuid().ToString() + fileName +fileExtension; // 保存文件名称 fileData.SaveAs(filePath + fileName + fileExtension); return Json(new { Success = true, FileName = fileName, SaveName = saveName }); } catch (Exception ex) { return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet); } } else { return Json(new { Success = false, Message = "请选择要上传的文件!" }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 将服务器的数据导入数据库 /// </summary> /// <returns></returns> public ActionResult toDB() { string filePath = Server.MapPath("~/Uploads/uploadExcel/");//将导入的文件路径 if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string[] filename = Directory.GetFiles(filePath);//将导入的文件 string fileName = Path.GetFileName(filename[0]);//将导入的文件名称 Jxd.Mvc.Domain.Model.FileInfo filedate = new Jxd.Mvc.Domain.Model.FileInfo(); filedate.AnnexName = fileName; filedate.AnnexPath = filePath + fileName; this.EquipmentService.toDB(filedate, filePath); return null; } /// <summary> /// 模板下载 /// filename : person /// </summary> public ActionResult DownFile(string filePath, string fileName) { string path = Server.MapPath("~/" + filePath);//路径 FileStream fs = new FileStream(path, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); Response.Charset = "UTF-8"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName)); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); return new EmptyResult(); } 四、Dao /// <summary> /// 将服务器文件导入数据库 /// </summary> /// <param name="filedate"></param> /// <param name="filePath"></param> public void toDB(Jxd.Mvc.Domain.Model.FileInfo filedate,string filePath) { try { string fileName = filedate.AnnexName; string path = filedate.AnnexPath; ISheet sheet = null; IWorkbook workbook = null; FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read); if (fileName.IndexOf(".xlsx") > 0) { workbook = new XSSFWorkbook(stream); } else if (fileName.IndexOf(".xls") > 0) { workbook = new HSSFWorkbook(stream); } if (sheet == null) { sheet = workbook.GetSheetAt(0); //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet } if(sheet != null) { StringBuilder sql = null; List<SqlParameter> para = null; DBHelper db = null; DataTable dt = new DataTable(); //设置database的栏位 for (int i = 0; i <= 18; i++) { DataColumn field = null; switch (i) { case 0: field = new DataColumn("EquipmentId"); dt.Columns.Add(field); continue;//电机/泵主键 case 1: field = new DataColumn("EquipmentName"); dt.Columns.Add(field); continue;//名称 case 2: field = new DataColumn("UnitId"); dt.Columns.Add(field); continue;//所属机组 case 3: field = new DataColumn("InstallTime"); dt.Columns.Add(field); continue;//安装时间 case 4: field = new DataColumn("ForeBearing"); dt.Columns.Add(field); continue;//前轴承 case 5: field = new DataColumn("BackBearing"); dt.Columns.Add(field); continue;//后轴承 case 6: field = new DataColumn("Model"); dt.Columns.Add(field); continue;//型号 case 7: field = new DataColumn("ElectricalId"); dt.Columns.Add(field); continue;//所属电机(泵独有) case 8: field = new DataColumn("PerEquip"); dt.Columns.Add(field); continue;//外接设备 case 9: field = new DataColumn("iconField"); dt.Columns.Add(field); continue;// case 10: field = new DataColumn("Status"); dt.Columns.Add(field); continue;// case 11: field = new DataColumn("Item"); dt.Columns.Add(field); continue;//设备位号 case 12: field = new DataColumn("Style"); dt.Columns.Add(field); continue;//设备类型 case 13: field = new DataColumn("Voltage"); dt.Columns.Add(field); continue;//设备电压 case 14: field = new DataColumn("grade"); dt.Columns.Add(field); continue;//设备评级 case 15: field = new DataColumn("DateOfProduction"); dt.Columns.Add(field); continue;//出厂日期 case 16: field = new DataColumn("DurableYears"); dt.Columns.Add(field); continue;//使用年限 case 17: field = new DataColumn("Manufacturer"); dt.Columns.Add(field); continue;//生产厂家 case 18: field = new DataColumn("Code"); dt.Columns.Add(field); continue; } } //遍历数据 int first_row = sheet.FirstRowNum + 3; int last_row = sheet.LastRowNum; //--遍历行 for (int i = first_row; i <= last_row; i++) { IRow ergodic_row = sheet.GetRow(i); int num = ergodic_row.LastCellNum; DataRow dataRow_1 = dt.NewRow();//电机 DataRow dataRow_2 = dt.NewRow();//工作机 string company_name = ergodic_row.GetCell(5).StringCellValue;//单元格:单位名称 string plant_name = ergodic_row.GetCell(4).StringCellValue;//车间名称 string unit_name = ergodic_row.GetCell(1).StringCellValue;//装置名称 sql = new StringBuilder(); para = new List<SqlParameter>(); sql.Append(" SELECT DISTINCT d.idField FROM V_IMPORT a INNER JOIN V_IMPORT b ON a.idField = b.parentField"); sql.Append(" INNER JOIN V_IMPORT c ON b.idField =c.parentField INNER JOIN V_IMPORT d ON d.nameField = @UnitId"); sql.Append(" WHERE a.nameField =@company AND b.nameField =@plant"); para.Add(new SqlParameter("@UnitId", SqlDbType.VarChar, 50) { Value = unit_name }); para.Add(new SqlParameter("@company", SqlDbType.VarChar, 50) { Value = company_name }); para.Add(new SqlParameter("@plant", SqlDbType.VarChar, 50) { Value = plant_name }); DBHelper db2 = new DBHelper(); DataTable dt2 = db2.QueryData(sql.ToString(), para.ToArray()).Tables[0]; List<import> yniy = new List<import>(); yniy = ConvertHelper<import>.ConvertToList(dt2); dataRow_1[2] = yniy[0].idField; dataRow_2[2] = yniy[0].idField; dataRow_1[0] = Guid.NewGuid().ToString(); dataRow_2[0] = Guid.NewGuid().ToString(); string device_name = ergodic_row.GetCell(3).ToString(); dataRow_1[1] = device_name; dataRow_2[1] = device_name; string InstallTime1 = ergodic_row.GetCell(15).ToString(); string InstallTime2 = ergodic_row.GetCell(25).ToString(); dataRow_1[3] = InstallTime1; dataRow_2[3] = InstallTime2; string forebearing1 = ergodic_row.GetCell(8).ToString(); string backbearing1 = ergodic_row.GetCell(9).ToString(); string forebearing2 = ergodic_row.GetCell(18).ToString(); string backbearing2 = ergodic_row.GetCell(19).ToString(); sql = new StringBuilder(); para = new List<SqlParameter>(); sql.Append(" SELECT a.Id FROM TB_BEARINGINFORMATION a WHERE a.Model = @fore1"); sql.Append(" UNION ALL SELECT a.Id FROM TB_BEARINGINFORMATION a WHERE a.Model = @back1"); sql.Append(" UNION ALL SELECT a.Id FROM TB_BEARINGINFORMATION a WHERE a.Model = @fore2"); sql.Append(" UNION ALL SELECT a.Id FROM TB_BEARINGINFORMATION a WHERE a.Model = @back2"); para.Add(new SqlParameter("@fore1", SqlDbType.VarChar, 50) { Value = forebearing1 }); para.Add(new SqlParameter("@back1", SqlDbType.VarChar, 50) { Value = backbearing1 }); para.Add(new SqlParameter("@fore2", SqlDbType.VarChar, 50) { Value = forebearing2 }); para.Add(new SqlParameter("@back2", SqlDbType.VarChar, 50) { Value = backbearing2 }); db = new DBHelper(); DataTable dt3 = db.QueryData(sql.ToString(), para.ToArray()).Tables[0]; List<BearingInformation> list = new List<BearingInformation>(); list = ConvertHelper<BearingInformation>.ConvertToList(dt3); dataRow_1[4] = list[0].Id; dataRow_1[5] = list[1].Id; dataRow_2[4] = list[2].Id; dataRow_2[5] = list[3].Id; string model1 = ergodic_row.GetCell(6).ToString(); string model2 = ergodic_row.GetCell(16).ToString(); string style1 = ergodic_row.GetCell(7).ToString(); string style2 = ergodic_row.GetCell(17).ToString(); string grade1 = ergodic_row.GetCell(11).ToString(); string grade2 = ergodic_row.GetCell(21).ToString(); sql = new StringBuilder(); para = new List<SqlParameter>(); sql.Append(" SELECT a.DictId FROM TB_SYS_DATADICT a WHERE a.DictName = @model1"); sql.Append(" UNION ALL SELECT a.DictId FROM TB_SYS_DATADICT a WHERE a.DictName = @model2"); sql.Append(" UNION ALL SELECT a.DictId FROM TB_SYS_DATADICT a WHERE a.DictName =@style1"); sql.Append(" UNION ALL SELECT a.DictId FROM TB_SYS_DATADICT a WHERE a.DictName =@style2"); sql.Append(" UNION ALL SELECT a.DictId FROM TB_SYS_DATADICT a WHERE a.DictName =@grade1"); sql.Append(" UNION ALL SELECT a.DictId FROM TB_SYS_DATADICT a WHERE a.DictName =@grade2"); para.Add(new SqlParameter("@model1", SqlDbType.VarChar, 50) { Value = model1 }); para.Add(new SqlParameter("@model2", SqlDbType.VarChar, 50) { Value = model2 }); para.Add(new SqlParameter("@style1", SqlDbType.VarChar, 50) { Value = style1 }); para.Add(new SqlParameter("@style2", SqlDbType.VarChar, 50) { Value = style2 }); para.Add(new SqlParameter("@grade1", SqlDbType.VarChar, 50) { Value = grade1 }); para.Add(new SqlParameter("@grade2", SqlDbType.VarChar, 50) { Value = grade2 }); db = new DBHelper(); DataTable dt4 = db.QueryData(sql.ToString(), para.ToArray()).Tables[0]; List<DataDict> list2 = new List<DataDict>(); list2 = ConvertHelper<DataDict>.ConvertToList(dt4); dataRow_1[6] = list2[0].DictId; dataRow_2[6] = list2[1].DictId; dataRow_2[7] = dataRow_1[0]; dataRow_1[7] = null; dataRow_1[8] = null; dataRow_2[8] = null; dataRow_1[9] = "icon-elect"; dataRow_2[9] = "icon-pump"; dataRow_1[12] = list2[2].DictId; dataRow_2[12] = list2[3].DictId; dataRow_1[14] = list2[4].DictId; dataRow_2[14] = list2[5].DictId; string status = ergodic_row.GetCell(26).ToString(); string a = null; if (status == "启用") { a = "1"; } else { a = "0"; } dataRow_1[10] = a; dataRow_2[10] = a; string item = ergodic_row.GetCell(2).ToString(); dataRow_1[11] = item; dataRow_2[11] = item; string voltage1 = ergodic_row.GetCell(10).ToString(); string voltage2 = ergodic_row.GetCell(20).ToString(); string b = @"^[0-9]+(\\.[0-9]+)?$"; RegexStringValidator regex = new RegexStringValidator(b); try { regex.Validate(voltage1); regex.Validate(voltage2); } catch { continue; } dataRow_1[13] = voltage1; dataRow_2[13] = voltage2; string data_out1 = ergodic_row.GetCell(12).ToString(); string data_out2 = ergodic_row.GetCell(22).ToString(); dataRow_1[15] = data_out1; dataRow_2[15] = data_out2; string year1 = ergodic_row.GetCell(13).ToString(); string year2 = ergodic_row.GetCell(23).ToString(); dataRow_1[16] = year1; dataRow_2[16] = year2; string facture1 = ergodic_row.GetCell(14).ToString(); string facture2 = ergodic_row.GetCell(24).ToString(); dataRow_1[17] = facture1; dataRow_2[17] = facture2; sql = new StringBuilder(); para = new List<SqlParameter>(); sql.Append(" SELECT a.Code FROM TB_BASEEQ_POWERUNIT a WHERE a.UnitId = @unit"); para.Add(new SqlParameter("@unit", SqlDbType.VarChar, 50) { Value = dataRow_1[2] }); db = new DBHelper(); DataTable dt5 = db.QueryData(sql.ToString(), para.ToArray()).Tables[0]; List<PowerUnit> list3 = new List<PowerUnit>(); list3 = ConvertHelper<PowerUnit>.ConvertToList(dt5); dataRow_1[18] = list3[0].Code; dataRow_2[18] = list3[0].Code; dt.Rows.Add(dataRow_1); dt.Rows.Add(dataRow_2); } #region 将datatable导入数据库 string connString = ConfigurationManager.AppSettings["SqlConnection"]; SqlConnection conn = new SqlConnection(connString); conn.Open(); SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(conn); sqlbulkcopy.DestinationTableName = "TB_BASEEQ_EQUIPMENT"; sqlbulkcopy.NotifyAfter = dt.Rows.Count;//有几行数据 sqlbulkcopy.WriteToServer(dt);//数据导入数据库 sqlbulkcopy.Close();//关闭连接 Directory.Delete(filePath, true); #endregion } } catch(Exception ex){ throw ex; } } 总结:(1)导入文件时一定要给database设置栏位 (2)虚拟表的栏位名称可以与数据库表不一致,但顺序一定要一致,因为它是按照顺序依次插入的 (3)sheet.FirstRowNum = 0; sheet.FirstCellNum = 1; getRow、getCell从0开始 (4)excel中存在字段为0,不特殊处理的情况下会导入失败。 (5)设置的虚拟表字段不赋值时默认为空 (6)虚拟变字段为空时,dt.Rows[i][j].Tostring()=""; (7)虚拟表字段不赋值默认为null