1.导包
<dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>4.2.1</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
2.添加导出按钮
例如:<a id="exportXlsBtn" icon="icon-print" href="#" class="easyui-linkbutton" plain="true">导出Excel按钮</a>
3.添加导出事件 例如:
$("#exportXlsBtn").click(function(){ $("#searchForm").attr("action","../../report_exportXls.action"); $("#searchForm").submit(); });
4.编写ExportAction,添加exportXls方法 五步走.1.create a document 2.get a pdfWriter instance 3.open a docement 4.add content 5.close the document
@Action(value = "report_exportXls") public String exportXls() throws IOException { // 查询出满足当前条件 结果数据 List<WayBill> wayBills = wayBillService.findWayBills(model);
// 下载导出,一个流两个头 // 设置头信息 ServletActionContext.getResponse().setContentType("application/vnd.ms-excel");//设置文件类型MIME类型 String filename="运单数据.xls"; String agent = ServletActionContext.getRequest().getHeader("user-agent");//获得浏览器的类型 filename = FileUtils.encodeDownloadFilename(filename, agent);//进行编码 ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;filename=" + filename);
//生成PDF文件
Document document = new Document();
PdfWriter.getInstance(document,ServletActionContext.getResponse().getOutputStream); document.open();
//写PDF数据,
// 向document 生成pdf表格 Table table = new Table(6); table.setWidth(80); // 宽度 table.setBorder(1); // 边框 table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // 水平对齐方式 table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP); // 垂直对齐方式 // 设置表格字体 BaseFont cn = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false); Font font = new Font(cn, 10, Font.NORMAL, Color.BLUE); // 向表格写数据 // 表头 table.addCell(buildCell("编号", font)); table.addCell(buildCell("到达地", font)); table.addCell(buildCell("货物", font)); table.addCell(buildCell("数量", font)); table.addCell(buildCell("重量", font)); table.addCell(buildCell("配载要求", font)); // 表格数据 for (WorkOrderManage workOrderManage : workOrderManages) { table.addCell(buildCell(workOrderManage.getId(), font)); table.addCell(buildCell(workOrderManage.getArrivecity(), font)); table.addCell(buildCell(workOrderManage.getProduct(), font)); table.addCell(buildCell(workOrderManage.getNum().toPlainString(), font)); table.addCell(buildCell(workOrderManage.getWeight().toString(), font)); table.addCell(buildCell(workOrderManage.getFloadreqr(), font)); } // 向文档添加表格 document.add(table);
document.close();