itext和jxl实现PDF,CSV和Excel格式的文件的下载

1.将itext-1.4.8.jar和jxl.jar导入web工程的Lib下,这两个jar文件可以去csdn上搜索“j2eePractice”,这是我上传的工程文件,其lib下就有这两个jar包

2.表现层index.jsp

<%@ page language="java" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <form action="<%=path%>/download.do" method="post"> please choose the type of file to download: <select name="downType"> <option> 请选择 </option> <option value="PDF"> PDF </option> <option value="CSV"> CSV </option> <option value="Excel"> Excel </option> </select> <input type="submit" value="提交" /> <br /> <br/> <table > <tfoot align="right">file content</tfoot> <thead> <tr> <th> id </th> <th> name </th> <th> sex </th> <th> age </th> </tr> </thead> <tbody> <% for (int i = 1; i < 6; i++) { %> <tr> <td><%=String.valueOf(i)%></td> <td><%=String.valueOf((char) (i + 64))%></td> <td><%=i + 20%></td> <td> man </td> </tr> <% } %> </tbody> </table> </form> </body> </html>

3.所需javabean

Person.java

package com.zxc.struts.bean; public class Person { private String id; private String name; private int age; private String sex; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }

4.业务逻辑层

downloadAction.java

package com.zxc.struts.action; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jxl.Workbook; import jxl.write.Label; import jxl.write.NumberFormats; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.lowagie.text.Document; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; import com.zxc.struts.bean.Person; /** * MyEclipse Struts Creation date: 08-10-2010 * * XDoclet definition: * * @struts.action validate="true" */ public class downloadAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub String downType = request.getParameter("downType"); List list = new ArrayList(); for (int i = 1; i < 6; i++) { Person person = new Person(); person.setId(String.valueOf(i)); person.setName(String.valueOf((char) (i + 64))); person.setAge(i + 20); person.setSex("man"); list.add(person); } OutputStream os = null; String fname = "personlist"; if ("PDF".equals(downType)) { try { response.reset(); os = response.getOutputStream(); Document document = new Document(PageSize.A4, 50, 50, 50, 50); response.setContentType("application/pdf"); response.setHeader("Content-disposition", "attachment;filename=" + fname + ".pdf"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); int cols = list.size(); // 创建PDF表格 PdfPTable table = new PdfPTable(4); // 设置pdf表格的宽度 table.setTotalWidth(500); // 设置是否要固定其宽度 table.setLockedWidth(true); // 表头字体 Font thfont = new Font(); // 设置表头字体的大小 thfont.setSize(7); // 设置表头字体的样式 thfont.setStyle(Font.BOLD); Font tdfont = new Font(); tdfont.setSize(7); tdfont.setStyle(Font.NORMAL); // 设置水平对齐方式 table.setHorizontalAlignment(Element.ALIGN_MIDDLE); // 设置table的header table.addCell(new Paragraph("id", thfont)); table.addCell(new Paragraph("name", thfont)); table.addCell(new Paragraph("sex", thfont)); table.addCell(new Paragraph("age", thfont)); // 循环设置table的每一行 for (int i = 0; i < list.size(); i++) { Person p = (Person) list.get(i); table.addCell(new Paragraph(p.getId(), tdfont)); table.addCell(new Paragraph(p.getName(), tdfont)); table.addCell(new Paragraph(p.getSex(), tdfont)); table.addCell(new Paragraph(String.valueOf(p.getAge()), tdfont)); } document.add(table); document.close(); baos.writeTo(response.getOutputStream()); baos.close(); } catch (Exception e) { e.printStackTrace(); } } else if ("CSV".equals(downType)) { response.reset(); // 生成csv文件 response.setHeader("Content-disposition", "attachment;filename=" + fname + ".csv"); response.setContentType("text/csv"); response.setCharacterEncoding("UTF-8"); String sep = ","; try { os = response.getOutputStream(); os.write("id".getBytes()); os.write(sep.getBytes()); os.write("name".getBytes()); os.write(sep.getBytes()); os.write("sex".getBytes()); os.write(sep.getBytes()); os.write("age".getBytes()); os.write(sep.getBytes()); os.write(System.getProperty("line.separator").getBytes()); for (int i = 0; i < list.size(); i++) { Person p = (Person) list.get(i); os.write(p.getId().getBytes()); os.write((sep + "/t").getBytes()); os.write(p.getName().getBytes()); os.write((sep + "/t").getBytes()); os.write(p.getSex().getBytes()); os.write((sep + "/t").getBytes()); os.write(String.valueOf(p.getAge()).getBytes()); os.write((sep + "/t").getBytes()); os.write(sep.getBytes()); os.write(System.getProperty("line.separator").getBytes()); } os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } else if (downType.equals("Excel")) { response.reset(); // 生成xls文件 response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + fname + ".xls"); try { os = response.getOutputStream(); Label l = null; WritableWorkbook wbook = Workbook.createWorkbook(os); // 写sheet名称 WritableSheet sheet = wbook.createSheet("my excel file", 0); jxl.write.WritableFont wfc4 = new jxl.write.WritableFont( WritableFont.ARIAL, 9, WritableFont.NO_BOLD, false, jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK); jxl.write.WritableCellFormat wcfFC4 = new jxl.write.WritableCellFormat( wfc4); wcfFC4.setBackground(jxl.format.Colour.LIGHT_GREEN); int col = 0; sheet.setColumnView(col, 12); l = new Label(col, 0, "id", wcfFC4); sheet.addCell(l); col++; sheet.setColumnView(col, 12); l = new Label(col, 0, "name", wcfFC4); sheet.addCell(l); col++; sheet.setColumnView(col, 12); l = new Label(col, 0, "sex", wcfFC4); sheet.addCell(l); col++; sheet.setColumnView(col, 12); l = new Label(col, 0, "age", wcfFC4); sheet.addCell(l); // 设置字体样式 jxl.write.WritableFont wfc5 = new jxl.write.WritableFont( WritableFont.ARIAL, 9, WritableFont.NO_BOLD, false, jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK); jxl.write.WritableCellFormat wcfFC5 = new jxl.write.WritableCellFormat( wfc5); for (int i = 0; i < list.size(); i++) { Person p = (Person) list.get(i); int j = 0; l = new Label(j, i + 1, p.getId(), wcfFC5); sheet.addCell(l); j++; l = new Label(j, i + 1, p.getName(), wcfFC5); sheet.addCell(l); j++; l = new Label(j, i + 1, p.getSex(), wcfFC5); sheet.addCell(l); j++; l = new Label(j, i + 1, String.valueOf(p.getAge()), wcfFC5); sheet.addCell(l); j++; } // 写入流中 wbook.write(); wbook.close(); os.close(); } catch (Exception e) { e.printStackTrace(); } } return mapping.findForward(""); } }

5.struts-config.properties

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <form-beans /> <global-exceptions /> <global-forwards /> <action-mappings > <action path="/download" type="com.zxc.struts.action.downloadAction" cancellable="true" > </action> </action-mappings> <message-resources parameter="com.zxc.struts.ApplicationResources" /> </struts-config>

6.运行结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值