使用web程序导出Excel,PDF和CSV三种文件

写在前面

最近参与了一个后台的项目,时间一直比较忙,也连续有段时间没有记东西了。这两天做了个节目广告排期的导出功能,里面有用到三种文件的导出,分别是Excel,PDF和CSV文件。网上有很多文章讲解的比较详细,这里只是做下记录以便以后遇到查看。

导出Excel

之前用过POI的方式,这次用的是jxl,可以自行下载jxl.jar。一般自己也喜欢看可以直接跑的小demo,简洁明了下面就稍微把代码整理下:
下面给出个例子:

public final void exportSchedulesXls() {
        OutputStream os = null;
        WritableWorkbook wbook = null;
        try {
            response.reset(); //清空输出流
            response.setHeader("Content-disposition",
                    "attachment; filename=schedule.xlsx"); // 设定输出文件头
            response.setContentType("application/msexcel"); // 定义输出类型
            os = response.getOutputStream();
            wbook = Workbook.createWorkbook(os);
            //Excel表中第一个参数表示列,第二个表示行
            WritableSheet wsheet = wbook.createSheet("sheet1", 0);
            WritableFont bold = new WritableFont(WritableFont.createFont("Calibri"), 11, WritableFont.BOLD);
            //设置单元格格式
            WritableCellFormat titleCellFormat = new WritableCellFormat(bold);
            titleCellFormat.setAlignment(jxl.format.Alignment.CENTRE);
            titleCellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            //设置普通单元格
            WritableFont font = new WritableFont(WritableFont.createFont("Calibri"), 11, WritableFont.NO_BOLD);
            WritableCellFormat cellFormat = new WritableCellFormat(font);
            cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
            cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            cellFormat.setWrap(true);
            wsheet.addCell(new Label(0, 0, "排期列表", titleCellFormat));//标题
            wsheet.mergeCells(0, 0, 6, 0);//合并单元格
            wsheet.addCell(new Label(0, 1, "编号", titleCellFormat));
            wsheet.addCell(new Label(1, 1, "文件名", titleCellFormat));
            wsheet.addCell(new Label(2, 1, "广告类型", titleCellFormat));
            wsheet.addCell(new Label(3, 1, "频道包", titleCellFormat));
            wsheet.addCell(new Label(4, 1, "开始日期", titleCellFormat));
            wsheet.addCell(new Label(5, 1, "结束日期", titleCellFormat));
            wsheet.addCell(new Label(6, 1, "缩略图", titleCellFormat));
            //设置列宽
            wsheet.setColumnView(0, 5);
            wsheet.setColumnView(1, 50);
            wsheet.setColumnView(2, 20);
            wsheet.setColumnView(3, 22);
            wsheet.setColumnView(4, 25);
            wsheet.setColumnView(5, 25);
            wsheet.setColumnView(6, 25);
            List ssbList = new ArrayList<>();
            //设置单元格内容
            for(int i=0; i<100; i++) {
                wsheet.addCell(new Label(0, i + 2, String.valueOf(i+1), cellFormat));
                wsheet.addCell(new Label(1, i + 2, "CHANNEL BAR CHANGHWONG SD 170 pixel x 134 pixel.jpg", cellFormat));
                wsheet.addCell(new Label(2, i + 2, "ChannelBar", cellFormat));
                wsheet.addCell(new Label(3, i + 2, "", cellFormat));//Channel Packets
                wsheet.addCell(new Label(4, i + 2, "2016-05-01 00:13:00", cellFormat));
                wsheet.addCell(new Label(5, i + 2, "2016-05-10 00:13:00", cellFormat));
                wsheet.addCell(new Label(6, i + 2, "", cellFormat));//Thumbnails
            }
            wbook.write(); //从内存中写入文件中
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (wbook != null) {
                try {
                    wbook.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

实际中自行做变换。结果如下:
这里写图片描述

导出PDF

使用的是iText开源包,iText-2.1.7.jar, itext-rtf-2.1.7.jar和iTextAsian.jar,最后一个是处理中文字体。

public final void exportSchedulesPdf() {
        OutputStream os = null;
        Document document = new Document();
        try {
            response.reset(); //清空输出流
            response.setHeader("Content-disposition", "attachment; filename=schedule.pdf"); // 设定输出文件头
            response.setContentType("application/octet-stream"); // 定义输出类型
            os = response.getOutputStream();

            // 建立一个Document对象
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font keyfont = new Font(bfChinese, 11, Font.BOLD);// 设置字体大小
            Font textfont = new Font(bfChinese, 9, Font.NORMAL);// 设置字体大小
            document.setPageSize(PageSize.A4);// 设置页面大小
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, outputStream);
            document.open();
            PdfPTable table = PdfUtil.createTable(new float[]{1f, 4f, 2f, 2f, 2.5f, 2.5f, 2f});
            table.addCell(PdfUtil.createCell("标题xxxx", keyfont, Element.ALIGN_CENTER, 7, false));
            table.addCell(PdfUtil.createCell("编号", keyfont, Element.ALIGN_CENTER));
            table.addCell(PdfUtil.createCell("文件名", keyfont, Element.ALIGN_CENTER));
            table.addCell(PdfUtil.createCell("广告类型", keyfont, Element.ALIGN_CENTER));
            table.addCell(PdfUtil.createCell("频道包", keyfont, Element.ALIGN_CENTER));
            table.addCell(PdfUtil.createCell("开始日期", keyfont, Element.ALIGN_CENTER));
            table.addCell(PdfUtil.createCell("结束日期", keyfont, Element.ALIGN_CENTER));
            table.addCell(PdfUtil.createCell("缩略图", keyfont, Element.ALIGN_CENTER));
            //设置单元格
            for(int i=0; i<100; i++) {
                ScheduleServiceBean ssb = ssbList.get(i);
                String filepath = ssb.getFilepath();
                if(StringUtils.isNotBlank(filepath)) {
                    filepath = filepath.substring(filepath.lastIndexOf("/") + 1);
                }
                table.addCell(PdfUtil.createCell(String.valueOf(i+1), textfont));
                table.addCell(PdfUtil.createCell("CHANNEL BAR CHANGHWONG SD 170 pixel x 134 pixel.jpg", textfont));
                table.addCell(PdfUtil.createCell("ChannelBar", textfont));
                table.addCell(PdfUtil.createCell("", textfont));
                table.addCell(PdfUtil.createCell("2016-5-1 0:13:00", textfont));
                table.addCell(PdfUtil.createCell("2016-5-2 0:13:00", textfont));
                table.addCell(PdfUtil.createCell("", textfont));
            }
            document.add(table);
            document.close();
            response.setContentLength(outputStream.size());
            outputStream.writeTo(os);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

运行结果生成pdf文件如下:
这里写图片描述

导出CSV

这个比较简单,不用使用第三方插件,因为文本都是逗号隔开。

public final void exportSchedulesCsv() {
        OutputStream os = null;
        String adtype = request.getParameter("adtype");
        String exportDate = request.getParameter("exportdate");
        int iadtype = Integer.parseInt(adtype);
        try {
            //UserJson user = (UserJson)session.get("user");   
            //AddLogParam logparam = new AddLogParam("exportSchedule", "sumExportScheduleCsv", new Object[]{user.getUserName(), ""},"2",user.getUserName());
            response.reset(); //清空输出流
            response.setHeader("Content-disposition",
                    "attachment; filename=schedule.csv"); // 设定输出文件头
            response.setContentType("application/csv"); // 定义输出类型
            os = response.getOutputStream();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-M-d h:mm:ss");
            StringBuilder sb = new StringBuilder();
            //标题
            String header = "ID,File Name,AD Type,Channel Packets,Start Date,End Date,Thumbnails\r\n";
            sb.append(header);
            List ssbList = scheduleService.getAllSchedules(iadtype, exportDate);
            if(ssbList != null && ssbList.size() > 0) {
                for(int i=0; i
                    ScheduleServiceBean ssb = ssbList.get(i);
                    String filepath = ssb.getFilepath();
                    if(StringUtils.isNotBlank(filepath)) {
                        filepath = filepath.substring(filepath.lastIndexOf("/") + 1);
                    }
                    String channelPackets = " ";//Channel Packets暂时为空
                    sb.append(String.valueOf(i+1)).append(",")
                        .append(filepath).append(",")
                        .append(ssb.getAdtype()).append(",")
                        .append(channelPackets).append(",");
                    String beginDate = ssb.getStartdate() + " " + ssb.getStarttime();
                    sb.append(sdf1.format(sdf.parse(beginDate))).append(",");
                    String endDate = ssb.getEnddate() + " " + ssb.getEndtime();
                    sb.append(sdf1.format(sdf.parse(endDate))).append(",");
                    String thumbnails = " ";//Thumbnails暂时为空
                    sb.append(thumbnails).append("\r\n");
                }
                os.write(sb.toString().getBytes());
            }

            logparam.setState(Defines.EXPORT_SCHEDULE);
            logService.addLog(logparam, request);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

运行结果如下:
这里写图片描述

结束

就记这么多吧,虽然不是很详细,但是希望能帮到有需要的人。

你可能感兴趣的:(Web)