1. 刚接触mvc,我需要把页面显示的内容导出到一个Excel文件
把导出做成一个单独的form块 在form中指定提交到哪个控制器中的哪个Action方法。@using (Html.BeginForm()){ } 如果在BeginForm()没有参数的情况下默认是提交到和这个文件名一样的Action方法里面。@using (Html.BeginForm("Create", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" })) {}这是MVC3的form写法。在控制层写一个方法 这个方法里面在获取一次你页面显示的数据然后做处理导入到Excel中.
2. MVC导出数据到excel
1 视图里 和jquery结合做的 2 <input id="FileUpload" type="file" name="upload" style="width: 250px; background: White" class="easyui-validatebox" validtype="length[1,100]" /> 3 4 function OK() { //点击确定按钮的时候 5 var file = ($("#FileUpload").val()); 6 if (file == "") { 7 $.messager.alert('系统提示', '请选择将要上传的文件!'); 8 document.forms[0].submit(); 9 }10 else {11 var stuff = file.match(/^(.*)(\.)(.{1,8})$/)[3];12 if (stuff != 'xls') {13 alert('文件类型不正确,请选择.xls文件!');14 document.forms[0].submit();15 }16 else {17 $.ajax({18 type: "POST",19 url: "/后台路径/调用方法名",20 data: "file=" + file + "",21 success: function (result) {22 $.messager.alert('系统提示', result + "");23 }24 });25 }26 }27 28 后台://要确定excel的格式动态也可以.视情况而定29 30 public ActionResult UpLoad(string file)31 {32 string result = string.Empty;33 string strConn;34 strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + file + "; " + "Extended Properties=Excel 8.0;";35 OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);36 DataSet myDataSet = new DataSet();37 myCommand.Fill(myDataSet, "ExcelInfo");38 System.Data.DataTable tab = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable();39 // …用foreach把tab中数据添加到数据库 省略了如果是多表插入,可以调用存储过程.呵呵40 result="导入成功!";41 jsonResult json = new JsonResult();42 json.Data = result;43 return json;44 }
3. MVC架构下怎么导出数据为excel
1 视图里 和jquery结合做的 2 3 4 function OK() { //点击确定按钮的时候 5 var file = ($("#FileUpload").val()); 6 if (file == "") { 7 $.messager.alert('系统提示', '请选择将要上传的文件!'); 8 document.forms[0].submit(); 9 }
4. mvc 按钮导出excel没法导出到客户端
下载所需POI的jar包,并导入项目。添加一个User类,用于存放用户实体。添加一个UserController类。添加一个接口类UserService和实现类UserServiceImpl。这样就完成了excel导出至客户端浏览器,当然有时候也会用到导出excel至服务器上。只需要对本文步骤4中的第七步文件输出方式进行修改。然后去除controller类中的out参数设置就ok了。也可以看出其实两种方式只是最终保存方式不同,其他步骤是共通的。
5. 在mvc 中导出Excel 怎么让用户自己选择路径
functioninitXlsObj(){try{if(oXL==null)oXL=newActiveXObject("Excel.Application");}catch(e){alert("必须安装Excel电子表格软件,同时浏览器安全设置:AtiveX控件和插件->对没有标记为安全的ActiveX控件进行初始化和脚本运行,必须启用");return"";}oWB=oXL.Workbooks.Add;activeSheet=oWB.Worksheets(1);}functionfullData(){相应处理方法。。。。。。。。。。。activeSheet.Rows("1:1").Font.Size=14;activeSheet.Rows("1:1").Font.Bold=true;activeSheet.Columns.AutoFit;oXL.visible=true;}functionendXlsObj(){oXL.UserControl=true;//excel交由用户控制//oWB.Close(savechanges=false);//这句会关闭sheet//oXL.Quit();//这句会提示关闭生成的excel文件oXL=null;oWB=null;activeSheet=null;}
6. mvc4 怎么样导出excel表格
大概有两种做法:1.把画面上的Html字串输出到档案供Client端下载(※开发快但缺点为 使用者开启该Excel档案会跳出警告视窗)2.刻苦刻难,用ADO.net搭配NPOI套件,建立Excel物件…用ADO.net塞资料…Response给Client端下载(※开发慢,但没有上述缺点) 本文介绍的是第1种方法※并不是在Controller里一口气把Html字串都组好再输出档案,虽然这做法也行…实作概念1.使用者按下汇出按钮2.用jQuery把Html Table字串存入hidden栏位,表单post到Action3.Action回传File即可Sample Code:View的Index.cshtml <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script type="text/javascript" src="@Url.Content("~/Scripts/jquery-2.0.0.min.js")"></script> <script type="text/javascript"> function exportExcel() { var sHtml = htmlEncode($("#MyTable")[0].outerHTML);//做html编码 $("input[name='hHtml']").val(sHtml); //表单提交 $("form[name='myForm']").submit(); } //↓出自:http://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding function htmlEncode(value) { //create a in-memory div, set it's inner text(which jQuery automatically encodes) //then grab the encoded contents back out. The div never exists on the page. return $('<div/>').text(value).html(); } </script> </head> <body> <table width="100%" border="1" cellpadding="0" cellspacing="0" id="MyTable"> <thead> <tr> <th>编号</th> <th>名称</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>测试1</td> </tr> <tr> <td>2</td> <td>测试2</td> </tr> <tr> <td>3</td> <td>测试3</td> </tr> </tbody> </table> <br /> <input type="button" value="导出" onclick="exportExcel();" /> </body> </html> @using (Html.BeginForm("ExportExcel", "Home", FormMethod.Post, new { name="myForm"})) { @Html.Hidden("hHtml") } HomeController using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace .Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult ExportExcel(FormCollection form) { string strHtml = form["hHtml"]; strHtml = HttpUtility.HtmlDecode(strHtml);//Html解码 byte[] b = System.Text.Encoding.Default.GetBytes(strHtml);//字串转byte阵列 return File(b, "application/vnd.ms-excel", "这是Excel.xls");//输出档案给Client端 } } } 执行结果,按下导出
7. asp.net mvc导出excel
ASP.NET MVC导出Excel首先下载 NPOI.dll 引用到项目中建议下载地址:http://download.csdn.net/detail/pukuimin1226/5851747前台代码:<a href='/Admin/NurseUser/Excel' target='_blank'>导出Excel</a>后台代码://导出excelpublic FileResult Excel(){//获取list数据var list = bll.NurseUserListExcel("", "ID asc");//创建Excel文件的对象NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();//添加一个sheetNPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");//给sheet1添加第一行的头部标题NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);row1.CreateCell(0).SetCellValue("ID");row1.CreateCell(1).SetCellValue("用户姓名");row1.CreateCell(2).SetCellValue("电话");row1.CreateCell(3).SetCellValue("注册时间");row1.CreateCell(4).SetCellValue("邀请人ID");row1.CreateCell(5).SetCellValue("邀请人名称");row1.CreateCell(6).SetCellValue("邀请人电话");row1.CreateCell(7).SetCellValue("总积分");row1.CreateCell(8).SetCellValue("已使用积分");row1.CreateCell(9).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].ID);rowtemp.CreateCell(1).SetCellValue(list[i].Name);rowtemp.CreateCell(2).SetCellValue(list[i].Phone);rowtemp.CreateCell(3).SetCellValue(list[i].CreateTime.Value.ToString());rowtemp.CreateCell(4).SetCellValue(list[i].InviterID.Value);rowtemp.CreateCell(5).SetCellValue(list[i].iName);rowtemp.CreateCell(6).SetCellValue(list[i].iPhone);rowtemp.CreateCell(7).SetCellValue(list[i].IntegralSum);rowtemp.CreateCell(8).SetCellValue(list[i].IntegralSy);rowtemp.CreateCell(9).SetCellValue(list[i].IntegralKy);}// 写入到客户端System.IO.MemoryStream ms = new System.IO.MemoryStream();book.Write(ms);ms.Seek(0, SeekOrigin.Begin);return File(ms, "application/vnd.ms-excel", "用户信息.xls");}excel文档就会自动下载下来
8. C#.net MVC求解决,导出word或者excel
如果没有合并的单元格导出至excel里要简单些 方法是:遍历table 把table里的数据在后台处理至datatable类型或其他类型,在后台导出文件,可以参考:http://blog.csdn.net/gisfarmer/article/details/3738959导出至word要复杂些 可以参考:http://www.cnblogs.com/koolay/articles/1398110.html
9. 如何修改spring mvc poi 导出excel文件
首先要导入spring相关包,poi,和fileupload包,我是使用maven构建的。 一.导入excel (1)使用spring上传文件a.前台页面提交<form name="excelImportForm" action="${pageContext.request.contextPath}/brand/importBrandSort" method="post" onsubmit="return checkImportPath();" enctype="multipart/form-data" id="excelImportForm"><input type="hidden" name="ids" id="ids"><div class="modal-body"><div class="row gap"><label class="col-sm-7 control-label"><input class="btn btn-default" id="excel_file" type="file" name="filename" accept="xls"/></label><div class="col-sm-3"><input class="btn btn-primary" id="excel_button" type="submit" value="导入Excel"/></div></div></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal" onClick="uncheckBoxes();">取消</button></div>b.后台spring的controller进行相关操作,这里主要讲的是使用spring上传文件,和读取文件信息。使用spring上传文件之前,需要配置bean。<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>@RequestMapping(value = "/importBrandSort", method = RequestMethod.POST)public ModelAndView importBrandSort(@RequestParam("filename") MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception {String temp = request.getSession().getServletContext().getRealPath(File.separator)+ "temp"; // 临时目录File tempFile = new File(temp);if (!tempFile.exists()) {tempFile.mkdirs();}DiskFileUpload fu = new DiskFileUpload();fu.setSizeMax(10 * 1024 * 1024); // 设置允许用户上传文件大小,单位:位fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:位fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录// 开始读取上传信息//int index = 0;/*List fileItems = null;try {fileItems = fu.parseRequest(request);}catch (Exception e) {e.printStackTrace();}Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件FileItem fileItem = null;while (iter.hasNext()) {FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表单信息if (!item.isFormField()) {fileItem = item;// index++;}}if (fileItem == null)return null;*/if (file == null)return null;logger.info(file.getOriginalFilename());String name = file.getOriginalFilename();// 获取上传文件名,包括路径//name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名long size = file.getSize();if ((name == null || name.equals("")) && size == 0)return null;InputStream in = file.getInputStream();List<BrandMobileInfoEntity> BrandMobileInfos = brandService.importBrandPeriodSort(in);// 改为人工刷新缓存KeyContextManager.clearPeriodCacheData(new// PeriodDimensions());// 清理所有缓存int count = BrandMobileInfos.size();String strAlertMsg ="";if(count!=0){strAlertMsg= "成功导入" + count + "条!";}else {strAlertMsg = "导入失败!";}logger.info(strAlertMsg);//request.setAttribute("brandPeriodSortList", BrandMobileInfos);//request.setAttribute("strAlertMsg", strAlertMsg);request.getSession().setAttribute("msg",strAlertMsg);return get(request, response);//return null;}代码中的注释部分是如果不使用spring的方式,如何拿到提交过来的文件名(需要是要apache的一些工具包),其实使用spring的也是一样,只是已经做好了封装,方便我们写代码。 代码中的后半部分是读取完上传文文件的信息和对数据库进行更新之后,输出到前台页面的信息。上述代码中: InputStream in = file.getInputStream();List<BrandMobileInfoEntity> BrandMobileInfos = brandService.importBrandPeriodSort(in);读取excel的信息。 (2)使用poi读取excela.更新数据库@Overridepublic List<BrandMobileInfoEntity> importBrandPeriodSort(InputStream in) throws Exception {List<BrandMobileInfoEntity> brandMobileInfos = readBrandPeriodSorXls(in);for (BrandMobileInfoEntity brandMobileInfo : brandMobileInfos) {mapper.updateByConditions(brandMobileInfo);}return brandMobileInfos;}这部分是sevice层的代码,用于读取excel信息之后更新数据库数据,我这里是使用mybatis。定义一个类BrandMobileInfoEntity,用与保存excel表每一行的信息,而List< BrandMobileInfoEntity > 则保存了全部信息,利用这些信息对数据库进行更新。 b.读取excel信息private List<BrandMobileInfoEntity> readBrandPeriodSorXls(InputStream is)throws IOException, ParseException {HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);List<BrandMobileInfoEntity> brandMobileInfos = new ArrayList<BrandMobileInfoEntity>();BrandMobileInfoEntity brandMobileInfo;// 循环工作表Sheetfor (int numSheet = 0;numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);if (hssfSheet == null) {continue;}// 循环行Rowfor (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {brandMobileInfo = new BrandMobileInfoEntity();HSSFRow hssfRow = hssfSheet.getRow(rowNum);for (int i = 0; i < hssfRow.getLastCellNum(); i++) {HSSFCell brandIdHSSFCell = hssfRow.getCell(i);if (i == 0) {brandMobileInfo.setBrandId(Integer.parseInt(getCellValue(brandIdHSSFCell)));} else if (i == 1) {continue;} else if (i == 2) {brandMobileInfo.setMobileShowFrom(Integer.parseInt(getCellValue(brandIdHSSFCell)));} else if (i == 3) {brandMobileInfo.setMobileShowTo(Integer.parseInt(getCellValue(brandIdHSSFCell)));} else if (i == 4) {brandMobileInfo.setSellMarkValue(getCellValue(brandIdHSSFCell));} else if (i == 5) {brandMobileInfo.setWarehouse(getCellValue(brandIdHSSFCell));} else if (i == 6) {brandMobileInfo.setSortA1(Integer.parseInt(getCellValue(brandIdHSSFCell)));} else if (i == 7) {brandMobileInfo.setSortA2(Integer.parseInt(getCellValue(brandIdHSSFCell)));} else if (i == 8) {brandMobileInfo.setSortB(Integer.parseInt(getCellValue(brandIdHSSFCell)));} else if (i == 9) {brandMobileInfo.setSortC10(Integer.parseInt(getCellValue(brandIdHSSFCell)));}else if (i == 10) {brandMobileInfo.setSortC(Integer.parseInt(getCellValue(brandIdHSSFCell)));} else if (i == 11) {brandMobileInfo.setHitA(getCellValue(brandIdHSSFCell));} else if (i == 12) {brandMobileInfo.setHitB(getCellValue(brandIdHSSFCell));} else if (i == 13) {brandMobileInfo.setHitC(getCellValue(brandIdHSSFCell));} else if (i == 14) {brandMobileInfo.setCustomSellType(getCellValue(brandIdHSSFCell));}else if (i == 15){continue;}else if (i == 16) {brandMobileInfo.setChannelId(Integer.parseInt(getCellValue(brandIdHSSFCell)));}}brandMobileInfos.add(brandMobileInfo);}}return brandMobileInfos;}这种代码有点搓,还没有优化,可以大概看到是怎么读取信息的。 (3)使用mybatis更新数据。
10. springmvc使用poi导出excel需要什么jar
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。这里的方法支持导出excel至项目所在服务器,或导出至客户端浏览器供用户下载,下面我把两个实例都放出来。1.下载所需POI的jar包,并导入项目。2.添加一个User类,用于存放用户实体,类中内容如下:1 package com.mvc.po; 2 3 public class User { 4 private int id; 5 private String name; 6 private String password; 7 private int age; 8 9 public User() {10 11 }12 13 public User(int id, String name, String password, int age) {14 this.id = id;15 this.name = name;16 this.password = password;17 this.age = age;18 }19 public int getId() {20 return id;21 }22 public void setId(int id) {23 this.id = id;24 }25 public String getName() {26 return name;27 }28 public void setName(String name) {29 this.name = name;30 }31 public String getPassword() {32 return password;33 }34 public void setPassword(String password) {35 this.password = password;36 }37 public int getAge() {38 return age;39 }40 public void setAge(int age) {41 this.age = age;42 }43 }3.添加一个UserController类,类中内容如下:1 package com.mvc.controller; 2 3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 6 import javax.servlet.ServletOutputStream; 7 import javax.servlet.http.HttpServletResponse; 8 9 import org.springframework.stereotype.Controller;10 import org.springframework.beans.factory.annotation.Autowired;11 import org.springframework.web.bind.annotation.RequestMapping;12 import org.springframework.web.bind.annotation.ResponseBody;13 14 import com.mvc.po.User;15 import com.mvc.service.UserService;16 17 @Controller18 public class UserController {19 20 @Autowired21 private UserService userService;22 23 @RequestMapping("/export.do")24 public @ResponseBody String export(HttpServletResponse response){ 25 response.setContentType("application/binary;charset=UTF-8");26 try{27 ServletOutputStream out=response.getOutputStream();28 String fileName=new String(("UserInfo "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes(),"UTF-8");29 response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");30 String[] titles = { "用户编号", "用户姓名", "用户密码", "用户年龄" }; 31 userService.export(titles, out);32 return "success";33 } catch(Exception e){34 e.printStackTrace();35 return "导出信息失败";36 }37 }38 }4.添加一个接口类UserService和实现类UserServiceImpl,类中内容如下:1 package com.mvc.service;2 3 import javax.servlet.ServletOutputStream;4 import com.mvc.po.User;5 6 public interface UserService {7 public void export(String[] titles, ServletOutputStream out);8 }1 package com.mvc.service.impl; 2 3 import java.text.SimpleDateFormat; 4 import java.util.List; 5 6 import javax.servlet.ServletOutputStream; 7 8 import com.mvc..UserDAO; 9 import com.mvc.po.User;10 import com.mvc.service.UserService;11 12 import org.apache.poi.hssf.usermodel.HSSFCell;13 import org.apache.poi.hssf.usermodel.HSSFCellStyle;14 import org.apache.poi.hssf.usermodel.HSSFRow;15 import org.apache.poi.hssf.usermodel.HSSFSheet;16 import org.apache.poi.hssf.usermodel.HSSFWorkbook;17 import org.springframework.beans.factory.annotation.Autowired;18 import org.springframework.stereotype.Service;19 20 @Service21 public class UserServiceImpl implements UserService {22 23 @Autowired24 private UserDAO userDAO;25 26 @Override27 public void export(String[] titles, ServletOutputStream out) { 28 try{29 // 第一步,创建一个workbook,对应一个Excel文件30 HSSFWorkbook workbook = new HSSFWorkbook();31 // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet32 HSSFSheet hssfSheet = workbook.createSheet("sheet1");33 // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short34 HSSFRow hssfRow = hssfSheet.createRow(0);35 // 第四步,创建单元格,并设置值表头 设置表头居中36 HSSFCellStyle hssfCellStyle = workbook.createCellStyle();37 //居中样式38 hssfCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);39 40 HSSFCell hssfCell = null;41 for (int i = 0; i < titles.length; i++) {42 hssfCell = hssfRow.createCell(i);//列索引从0开始43 hssfCell.setCellValue(titles[i]);//列名144 hssfCell.setCellStyle(hssfCellStyle);//列居中显示 45 }46 47 // 第五步,写入实体数据 48 List<User> users = userDAO.query(); 49 50 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");51 if(users != null && !users.isEmpty()){52 for (int i = 0; i < users.size(); i++) {53 hssfRow = hssfSheet.createRow(i+1); 54 User user = users.get(i);55 56 // 第六步,创建单元格,并设置值57 int userid = 0;58 if(user.getId() != 0){59 userid = user.getId();60 }61 hssfRow.createCell(0).setCellValue(userid);62 String username = "";63 if(user.getName() != null){64 username = user.getName();65 }66 hssfRow.createCell(1).setCellValue(username);67 String password = "";68 if(user.getPassword() != null){69 password = user.getPassword();70 }71 hssfRow.createCell(2).setCellValue(password);72 int age = 0;73 if(user.getAge() != 0){74 age = user.getAge();75 }76 hssfRow.createCell(3).setCellValue(age);77 }78 }79 80 // 第七步,将文件输出到客户端浏览器81 try {82 workbook.write(out);83 out.flush();84 out.close();85 86 } catch (Exception e) {87 e.printStackTrace();88 }89 }catch(Exception e){90 e.printStackTrace();91 throw new Exception("导出信息失败!");92 } 93 }94 }5.添加一个接口类UserDAO和实现类UserDAOImpl,类中内容如下:1 package com.mvc.;2 3 import java.util.List;4 import com.mvc.po.User;5 6 public interface UserDAO {7 List<User> query(); 8 }1 package com.mvc..impl; 2 3 import java.util.List; 4 import java.sql.ResultSet; 5 import java.sql.SQLException; 6 7 import com.mvc..UserDAO; 8 import com.mvc.po.User; 9 10 import org.springframework.stereotype.Repository;11 import org.springframework.beans.factory.annotation.Autowired;12 import org.springframework.jdbc.core.JdbcTemplate;13 import org.springframework.jdbc.core.RowMapper;14 15 @Repository16 public class UserDAOImpl implements UserDAO {17 18 @Autowired19 private JdbcTemplate jdbcTemplate;20 21 public List<User> query() {22 return this.jdbcTemplate.query("select * from student",23 new RowMapper<User>() {24 public User mapRow(ResultSet rs, int arg1)25 throws SQLException {26 return new User(rs.getInt("sId"),27 rs.getString("sName"), rs.getString("sPwd"), rs28 .getInt("sAge"));29 }30 });31 }32 }这样就完成了excel导出至客户端浏览器,当然有时候也会用到导出excel至服务器上。只需要对本文步骤4中的第七步文件输出方式进行修改,如下:1 // 第七步,将文件存到指定位置2 try {3 FileOutputStream fileOutputStream = new FileOutputStream("C:/user.xls");//指定路径与名字和格式4 workbook.write(fileOutputStream);//讲数据写出去5 fileOutputStream.close();//关闭输出流6 } catch (Exception e) {7 e.printStackTrace();8 }然后去除controller类中的out参数设置就ok了。也可以看出其实两种方式只是最终保存方式不同,其他步骤是共通的。
未经允许不得转载:山九号 » mvc导出excel文件|aspnet mvc导出excel