java 生成简单word(利用Itext工具),生成简单Excel,以及下载笔记

1.java 生成简单word(包含图片表格)

pom中加入itext 相关依赖

<dependency>
       <groupId>com.lowagie</groupId>
        <artifactId>itext</artifactId>
       <version>2.1.7</version>
</dependency>
        
 <dependency>
        <groupId>com.lowagie</groupId>
        <artifactId>itext-rtf</artifactId>
        <version>2.1.7</version>
</dependency>

2.java相关代码(数据与图片可以忽略)

/**
     * 新建报告(报告名字。图片。新闻id)
     * 
     * @throws JSONException
     */
    @Override
    public String addReport(String[] img, String[] newsId, String reportName, String loginId, String path,
            String imgPath) {

        Long name = System.currentTimeMillis();
        String filePath = path + File.separator + name + ".doc";
        File file = new File(filePath);

        Report report = new Report();

        report.setLoginId(loginId);
        report.setReportName(reportName);
        report.setDownUrl(filePath);

        fileDao.addReport(report);

        System.out.println("插入报告成功" + report.getReportNo());
     
        Document document = new Document(PageSize.A4);

        try {
            RtfWriter2.getInstance(document, new FileOutputStream(file));
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        document.open();
        BaseFont bfChinese = null;
        try {
            bfChinese = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException | IOException e1) {
            e1.printStackTrace();
        }
        Font titleFont = new Font(bfChinese, 22, Font.BOLD);
        Font contextFont = new Font(bfChinese, 10, Font.NORMAL);
        Paragraph title = new Paragraph("统计报告", titleFont);
        title.setAlignment(Element.ALIGN_CENTER);

        // 红色的线
        RtfShapePosition position;
        position = new RtfShapePosition(150, 0, 10400, 170);
        position.setXRelativePos(RtfShapePosition.POSITION_X_RELATIVE_MARGIN);
        position.setYRelativePos(RtfShapePosition.POSITION_Y_RELATIVE_PARAGRAPH);
        RtfShape shape = new RtfShape(RtfShape.SHAPE_RECTANGLE, position);
        RtfShapeProperty property = new RtfShapeProperty(RtfShapeProperty.PROPERTY_LINE_COLOR, Color.RED);
        shape.setProperty(property);

        Paragraph p1 = new Paragraph(shape);
        try {
            // logo
            Image imglogo = Image.getInstance(imgPath + File.separator + "dfgx.jpg");
            imglogo.setAlignment(Image.LEFT);// 设置图片显示位置
            imglogo.scaleAbsolute(80, 50);// 直接设定显示尺寸
            document.add(imglogo);
            document.add(title);
            document.add(p1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Table table = null;
        try {
            table = new Table(4);
            int width[] = { 40, 30, 15, 15 };// 设置每列宽度比例
            table.setWidths(width);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        table.setBorderWidth(1);
        table.setBorderColor(Color.BLACK);
        table.setPadding(0);
        table.setSpacing(0);
        try {
            table.addCell("标题");
            table.addCell("链接");
            table.addCell("渠道");
            table.addCell("时间");
        } catch (BadElementException e1) {
            e1.printStackTrace();
        }
        List<Object> list = estoWeb.SelectId(newsId);
        String time = "";
        String titleinfo = "";
        String url = "";
        String channel = "";
        try {
            for (Object string : list) {
                JSONObject json = null;
                json = new JSONObject(String.valueOf(string));
                channel = (String) json.get("webCell");
                titleinfo = (String) json.get("titleCell");
                url = (String) json.get("linkCell");
                time = (String) json.get("dateCell");
                table.addCell(new Paragraph(titleinfo));
                table.addCell(new Paragraph(url));
                table.addCell(new Paragraph(channel));
                table.addCell(new Paragraph(time));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            document.add(table);
        } catch (DocumentException e1) {
            e1.printStackTrace();
        }

        for (String string : img) {
            Map<String, Object> map = fileDao.findReportPath(string);
            System.out.println(map.get("PIC_PATH"));
            Image img1 = null;
            try {
                img1 = Image.getInstance(imgPath + File.separator + String.valueOf(map.get("PIC_PATH")));
            } catch (BadElementException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            img1.setAbsolutePosition(0, 0);
            img1.setAlignment(Image.ALIGN_CENTER);// 设置图片显示位置
            img1.scaleAbsolute(360, 180);// 直接设定显示尺寸
            try {
                document.add(img1);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }

        document.close();

        return "ok";
    }

3.生成简单Excel(参考 :http://blog.csdn.net/yongqingmiao/article/details/7179452)

pom加入相关依赖

<dependency>
            <groupId>jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6</version>
</dependency>
        

4.java代码

File file;
        WritableWorkbook wwb;
        try {
            file = new File(imgpath + File.separator + "news.xls");
            wwb = Workbook.createWorkbook(file);
            WritableSheet ws = wwb.createSheet("页1", 0);
            ws.addCell(new Label(0, 0, "时间"));
            ws.addCell(new Label(1, 0, "标题"));
            ws.addCell(new Label(2, 0, "链接"));
            ws.addCell(new Label(3, 0, "渠道"));
            List<Object> list = estoWeb.SelectId(newsId);
            String time = "";
            String titleinfo = "";
            String url = "";
            String channel = "";
            try {
                for (int i = 0; i < list.size(); i++) {
                    JSONObject json = null;
                    json = new JSONObject(String.valueOf(list.get(i)));
                    channel = (String) json.get("webCell");
                    titleinfo = (String) json.get("titleCell");
                    url = (String) json.get("linkCell");
                    time = (String) json.get("dateCell");

                    
                    ws.addCell(new Label(0, i + 1, time));
                    ws.addCell(new Label(1, i + 1, titleinfo));
                    ws.addCell(new Label(2, i + 1, url));
                    ws.addCell(new Label(3, i + 1, channel));
                    

                }

                wwb.write();
                wwb.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

5.下载demo(相关文件名参数参考)

InputStream inputStream = null;
        OutputStream os = null;

        res.setCharacterEncoding("utf-8");
        res.setContentType("multipart/form-data");
        res.setHeader("Content-Disposition", "attachment;filename=\"" + "news.xls" + "\"");

        try {
            // 下载文件
            inputStream = new FileInputStream(new File(imgpath + File.separator + "news.xls"));
            os = res.getOutputStream();

            byte[] b = new byte[4096];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        } finally {
            try {
                os.flush();
                os.close();
                inputStream.close();
                if (new File(imgpath + File.separator + "news.xls").exists()) {
                    new File(imgpath + File.separator + "news.xls").delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
                return "false";
            }

        }

 

posted @ 2017-05-31 10:31  丨Mars  阅读(2551)  评论(0编辑  收藏  举报