Java创建excel表格并下载

来源:互联网 发布:php int加括号 编辑:程序博客网 时间:2024/06/04 18:07
<pre name="code" class="java">public void toExcel(HttpServletResponse response){//创建工作薄WritableWorkbook book = null;//创建工作流OutputStream os = null;response.setCharacterEncoding("utf-8");//清空输出流response.reset();//设置弹出对话框,定义输出类型为excel文件response.setContentType("application/msexecl");//设置工作表标题response.setHeader("Content-Disposition", "attachment;filename=test.xls");try {//取得输出流os = response.getOutputStream();//初始化工作表book = Workbook.createWorkbook(os);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}//创建新的一页WritableSheet sheet = book.createSheet("名字", 0);try {//创建显示的内容,创建单元格,第一个参数为列坐标,第二个参数为行坐标,第三个参数为内容sheet.addCell(new jxl.write.Label(0, 0, "姓名"));sheet.addCell(new jxl.write.Label(1, 0, "年龄"));sheet.addCell(new jxl.write.Label(2, 0, "性别"));//如果是数据库里面读取数据的话,从数据库里面查询出listList<Map<String, String>> list = new ArrayList<Map<String,String>>();for (int i = 0; i < list.size(); i++) {sheet.addCell(new jxl.write.Label(0, i+1, list.get(i).get("NAME")));sheet.addCell(new jxl.write.Label(1, i+1, list.get(i).get("AGE")));sheet.addCell(new jxl.write.Label(2, i+1, list.get(i).get("SEX")));}} catch (RowsExceededException e) {e.printStackTrace();} catch (WriteException e) {e.printStackTrace();}try {book.write();book.close();} catch (WriteException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
<span style="font-size:18px;color:#ff6666;"><strong>注意:</strong></span><p style="margin: 10px auto; padding-top: 0px; padding-bottom: 0px; line-height: 19.5px; font-size: 13px; font-family: Verdana, Arial, Helvetica, sans-serif; background-color: rgb(254, 254, 242);"><span style="white-space:pre"></span><span style="color:#ff0000;">Content-disposition</span> 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。当 Internet Explorer 接收到头时,它会激活<span style="margin: 0px; padding: 0px;">文件下载</span>对话框,它的文件名框自动填充了头中指定的文件名。(请注意,这是设计导致的;无法使用此功能将文档保存到用户的计算机上,而不向用户询问保存位置。)   服务端向客户端游览器发送文件时,如果是浏览器支持的文件类型,一般会默认使用浏览器打开,比如txt、jpg等,会直接在浏览器中显示,如果需要提示用户保存,就要利用Content-Disposition进行一下处理,关键在于一定要加上<span style="color:#ff0000;">attachment</span>:Response.AppendHeader("Content-Disposition","attachment;filename=FileName.txt");</p><p style="margin: 10px auto; padding-top: 0px; padding-bottom: 0px; line-height: 19.5px; font-size: 13px; font-family: Verdana, Arial, Helvetica, sans-serif; background-color: rgb(254, 254, 242);"><span style="white-space:pre"></span></p>
                                             
0 0