//导出excle 设备效率 public JsonResult Exporta() { var jser = new JavaScriptSerializer(); string js1 = Request.Params["rows"].ToString(); string js2 = Request.Params["columns"].ToString(); DataTable dt1 = JsonToDataTable.JsToDataTab(js1); DataTable dt2 = JsonToDataTable.JsToDataTab(js2); //反序列化 //var objList1 = jser.DeserializeObject(Request.Params["rows"]); //Object objList2 = jser.DeserializeObject(Request.Params["columns"]); //foreach (DataRow dr in dt2.Rows) //{ // string value = dr["Title"].ToString(); // DataColumn col = new DataColumn(); // col.ColumnName = value; // col.DataType = System.Type.GetType("System.String"); // dt1.Columns.Add(col); //} //创建Excel文件的对象 NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); HSSFSheet sheet = book.CreateSheet("Sheet1"); //给sheet1添加第一行的头部标题 HSSFRow row1 = sheet.CreateRow(0); int i = -1; foreach (DataRow dr in dt2.Rows) { i++; string value = dr["title"].ToString(); row1.CreateCell(i).SetCellValue(value); } if (dt1 != null) { //将数据逐步写入sheet1各个行 for (int j = 0; j < dt1.Rows.Count; j++) { HSSFRow rowtemp = sheet.CreateRow(j + 1); rowtemp.CreateCell(0).SetCellValue(dt1.Rows[j]["WorkShopName"].ToString()); rowtemp.CreateCell(1).SetCellValue(dt1.Rows[j]["OpenRate"].ToString()); rowtemp.CreateCell(2).SetCellValue(dt1.Rows[j]["RunRate"].ToString()); rowtemp.CreateCell(3).SetCellValue(dt1.Rows[j]["UOE2"].ToString()); rowtemp.CreateCell(4).SetCellValue(dt1.Rows[j]["UOE3"].ToString()); rowtemp.CreateCell(5).SetCellValue(dt1.Rows[j]["UOE4"].ToString()); } } // 写入到客户端 // 写入到客户端 if (Directory.Exists(Server.MapPath("~/ExportFiles/")) == false)//如果不存在就创建file文件夹 { Directory.CreateDirectory(Server.MapPath("~~/ExportFiles/")); } //判断文件的存在 if (System.IO.File.Exists(Server.MapPath("~/ExportFiles/设备效率.xls"))) { Response.Write("Yes"); //存在文件 } else { Response.Write("No"); //不存在文件 System.IO.File.Create(Server.MapPath("~/ExportFiles/设备效率.xls")).Close();//创建该文件 } try { FileStream fs = new FileStream(Server.MapPath("~/ExportFiles/" + "设备效率.xls"), FileMode.Create); book.Write(fs); fs.Seek(0, SeekOrigin.Begin); fs.Flush(); fs.Close(); } catch (Exception) { throw; } //return File(fs, "application/vnd.ms-excel", "1.xls"); return Json(new { mes = "", state = 1 }); }