跟小刀 学习java导出word

来源:互联网 发布:网络推广视频 编辑:程序博客网 时间:2024/04/30 09:20
  • 前一段时间客户经理要求让我们实现一个功能 就是java导出word 因为给的模板内容实在太多 报表呀.各种数据呀.都是几十个几十个的.导致我对待这个功能实现比较消极,一直在改别的需求..但是由于一些特殊的原因.还是决定要啃这块骨头了.在这里记下博客以防以后遇到了忘记怎么写了.
  • 首先非常感谢 csnd 的俩位大神 提供了例子 一个使用itext 生成了 word 一个使用 jfreechar 生成了报表..哈哈.是不是很有喜感….你不需要懂太具体. 只要完成功能就可以..虽然我的功能还没有完成.但是还是先写博客吧..
  • 其实开始的时候我是使用freemarker 模板导出的,研究了那个3天时间.后来发现..不是那么好用,容易把电脑卡死…
  • 上代码controller
  • // * 导出word 文档

    @RequestMapping(“/exportWord”)
    public @ResponseBody ResultMessage exportWord() {
    HttpServletRequest request = getRequest();
    HttpServletResponse response = getResponse();
    Document document = new Document(PageSize.A4);
    try {
    //这里有个问题本来是想用输出流,让用户自主选择下载路劲.目前还没有解决
    response.setContentType(“application/msword”);
    // RtfWriter2.getInstance(document, response.getOutputStream());
    teacherService.exportWord(request, document);

    } catch (Exception e) {    log.error("export word error", e);    return ResultMessage.successMsg("export word error");}document.close();return ResultMessage.successMsg("export word success", "");

    }

service

    public void exportWord(HttpServletRequest request, Document document) throws Exception{    System.out.println("执行");     //获取web 目录绝对路劲     String realPath =request.getSession().getServletContext().getRealPath("/");     String storePath = realPath +"exportWord/";//存储的路劲     CreateChart c = new CreateChart(storePath);     //创建一个名字一会添加到 word 里.     String loginPieName = System.currentTimeMillis()+".png";     String pieChartPath = c.makePieChart(loginPieName);     //生成word  文档.     Generate wt = new Generate(document);      wt.openDocument("e:\\dome2.doc");      SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年MM月dd 日");      wt.insertTitle("安苑校区阅读数据分析报告",            18, Font.BOLD, Element.ALIGN_CENTER);      wt.insertTitle("\n", 12, Font.BOLD, Element.ALIGN_LEFT);      wt.insertTitle("\n", 12, Font.BOLD, Element.ALIGN_LEFT);      wt.insertTitle("报告来源: 量分析平台 ", 12, Font.BOLD, Element.ALIGN_CENTER);      wt.insertTitle("\n", 12, Font.BOLD, Element.ALIGN_CENTER);      wt.insertTitle(sdf.format(new Date()), 12, Font.BOLD, Element.ALIGN_CENTER);      wt.insertTitle("说明", 12, Font.BOLD, Element.ALIGN_LEFT);      wt.insertContext("的数据来源于平台用户的真实使用数据,数据周期为2016年3月17日至2017年5月02日。 \n",            11, Font.NORMAL, Element.ALIGN_LEFT);      wt.insertContext("    本报告由附属小学发起生成,主要分析了学校和年级学生的阅读量、阅读质量等数据,以供学校及教师掌握本校的阅读情况及其在阅读推广中所取得的成绩\n",            11, Font.NORMAL, Element.ALIGN_LEFT);      wt.insertContext("报告的最后列出了本校阅读次数最多的50本图书,以及各年级阅读次数最多的20本图书。\n",            11, Font.NORMAL, Element.ALIGN_LEFT);      wt.insertContext("本报告由2个部分组成,包括:北京化工大学附属小学全校的乐优阅读平台使用状况分析、系统平台与北京化工大学附属小学全校阅读最多的图书对比(取前50本图书)。\n",            11, Font.NORMAL, Element.ALIGN_LEFT);      wt.insertContext("本报告涉及的术语解释:\n",            11, Font.NORMAL, Element.ALIGN_LEFT);      wt.insertContext("   阅读量是指学生的阅读数量,包括阅读积分、阅读本数和阅读字数。其中阅读积分是根据学生所阅读的图书的积分和对图书检测题作答取得的积分"            + "以及学生在书评、交流圈等栏目中得到的点赞数换算的积分奖励值之合,是衡量学生阅读量的核心标准。\n",            11, Font.NORMAL, Element.ALIGN_LEFT);      wt.insertContext("阅读质量是从学生对检测题目作答的一次通过率和平均正确率两个方面考量学生阅读的质量和达到的效果,"            + "也是老师和家长判断学生阅读精细度的标准之一,同时也是老师和家长了解学生阅读效果的依据。\n",            11, Font.NORMAL, Element.ALIGN_LEFT);      wt.insertTitle("第一部分  使用状况整体分析", 18, Font.BOLD, Element.ALIGN_CENTER);      wt.insertContext("小学注册于乐优阅读平台的时间为2017年03月17日,"            + "经过一段时间的使用,结合学生、教师、家长三类用户提供的真实阅读及交互数据给出本报告。\n",            11, Font.NORMAL, Element.ALIGN_LEFT);      wt.insertTitle("\t 一、乐优阅读平台用户参与状态", 18, Font.BOLD, Element.ALIGN_LEFT);      wt.insertContext("平台账号的人数为172人,其中有参与平台活动行为的人数为90人,参与度为52.33%。如图1所示。\n",            11, Font.NORMAL, Element.ALIGN_LEFT);      //第一个饼图..登录人数    wt.insertImg(pieChartPath, Image.ALIGN_CENTER, 50, 75, 100, 100, 100, 30);            wt.closeDocument();     }

生成 word 的代码 里面有写测试类

public class Generate {    private Document document;    private BaseFont bfChinese;    public BaseFont getBfChinese() {        return bfChinese;    }    public Generate(Document document) {        super();        this.document = document;    }    public void setBfChinese(BaseFont bfChinese) {        this.bfChinese = bfChinese;    }    public Document getDocument() {        return document;    }    public void setDocument(Document document) {        this.document = document;    }    public Generate(){        this.document = new Document(PageSize.A4);    }    /**     * @param filePath 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中     * @throws DocumentException     * @throws IOException     */    public void openDocument(String filePath) throws DocumentException,    IOException {//       建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中        //创建一个流 让用户自己选择目录application/msword        RtfWriter2.getInstance(this.document, new FileOutputStream(filePath));        this.document.open();     // 添加页眉             HeaderFooter header = new HeaderFooter(new Phrase("header"), false);             header.setAlignment(Rectangle.ALIGN_CENTER);             document.setHeader(header);            // 添加页脚             //(参数一)页脚的段落   和  (参数二)是否有页码             HeaderFooter footer = new HeaderFooter(new Phrase(" "), true);             footer.setAlignment(Rectangle.ALIGN_CENTER);             document.setFooter(footer); //       设置中文字体        this.bfChinese = BaseFont.createFont("STSongStd-Light",                "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);    }    /**     * @param titleStr 标题     * @param fontsize 字体大小     * @param fontStyle 字体样式     * @param elementAlign 对齐方式     * @throws DocumentException     */    public void insertTitle(String titleStr,int fontsize,int fontStyle,int elementAlign) throws DocumentException{        Font titleFont = new Font(this.bfChinese, fontsize, fontStyle);        Paragraph title = new Paragraph(titleStr);        // 设置标题格式对齐方式        title.setAlignment(elementAlign);        title.setFont(titleFont);        this.document.add(title);    }    /**     * @param contextStr 内容     * @param fontsize 字体大小     * @param fontStyle 字体样式     * @param elementAlign 对齐方式     * @throws DocumentException      */    public void insertContext(String contextStr,int fontsize,int fontStyle,int elementAlign) throws DocumentException{        // 正文字体风格        Font contextFont = new Font(bfChinese, fontsize, fontStyle);        Paragraph context = new Paragraph(contextStr);        //设置行距        context.setLeading(10f);        // 正文格式左对齐        context.setAlignment(elementAlign);        context.setFont(contextFont);        // 离上一段落(标题)空的行数        context.setSpacingBefore(5);        // 设置第一行空的列数        context.setFirstLineIndent(20);        document.add(context);    }    /*     * 测试清单     * */    public  void insertRiskTable() throws DocumentException{        Table aTable = new Table(6,3);        int width[] = { 10, 40, 17, 13, 10, 10 };        aTable.setWidths(width);// 设置每列所占比例        aTable.setWidth(100); // 占页面宽度 90%        aTable.setAlignment(Element.ALIGN_CENTER);// 居中显示        aTable.setAlignment(Element.ALIGN_MIDDLE);// 纵向居中显示        aTable.setAutoFillEmptyCells(true); // 自动填满        aTable.setBorderWidth(0); // 边框宽度        aTable.setBorderColor(new Color(0, 125, 255)); // 边框颜色        aTable.setPadding(2);// 衬距,看效果就知道什么意思了        aTable.setSpacing(3);// 即单元格之间的间距        aTable.setBorder(2);// 边框        Font fontChinese = new Font(bfChinese, 10, Font.BOLD);        Cell cell = new Cell(new Phrase("\n测试代码\n", fontChinese));        cell.setVerticalAlignment(Element.ALIGN_CENTER);        cell.setHorizontalAlignment(Element.ALIGN_CENTER);        cell.setBorderColor(new Color(0, 0, 0));        cell.setBackgroundColor(new Color(153, 204, 255));        aTable.addCell(cell);        Cell cell1 = new Cell(new Phrase("测试名称", fontChinese));        cell1.setVerticalAlignment(Element.ALIGN_CENTER);        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);        cell1.setBorderColor(new Color(0, 0, 0));        cell1.setBackgroundColor(new Color(153, 204, 255));        aTable.addCell(cell1);        Cell cell2 = new Cell(new Phrase("测试发生可能性", fontChinese));        cell2.setVerticalAlignment(Element.ALIGN_CENTER);        cell2.setHorizontalAlignment(Element.ALIGN_CENTER);        cell2.setBorderColor(new Color(0, 0, 0));        cell2.setBackgroundColor(new Color(255, 255, 0));        aTable.addCell(cell2);        Cell cell3 = new Cell(new Phrase("测试损失度", fontChinese));        cell3.setVerticalAlignment(Element.ALIGN_CENTER);        cell3.setHorizontalAlignment(Element.ALIGN_CENTER);        cell3.setBorderColor(new Color(0, 0, 0));        cell3.setBackgroundColor(new Color(255, 255, 0));        aTable.addCell(cell3);        Cell cell4 = new Cell(new Phrase("测试水平", fontChinese));        cell4.setVerticalAlignment(Element.ALIGN_CENTER);        cell4.setHorizontalAlignment(Element.ALIGN_CENTER);        cell4.setBorderColor(new Color(0, 0, 0));        cell4.setBackgroundColor(new Color(255, 255, 0));        aTable.addCell(cell4);        Cell cell5 = new Cell(new Phrase("测试等级", fontChinese));        cell5.setVerticalAlignment(Element.ALIGN_CENTER);        cell5.setHorizontalAlignment(Element.ALIGN_CENTER);        cell5.setBorderColor(new Color(0, 0, 0));        cell5.setBackgroundColor(new Color(255, 255, 0));        aTable.addCell(cell5);        for(int i=0;i<12;i++){            aTable.addCell(new Cell(i+""));        }               document.add(aTable);        document.add(new Paragraph("\n"));      }    /*     * 现状评估     * */    public void insertRiskEvaluationTable() throws DocumentException{        Table aTable = new Table(4,7);        int width1[] = { 5, 20, 8, 25};        aTable.setWidths(width1);// 设置每列所占比例        aTable.setWidth(100); // 占页面宽度 90%        aTable.setAlignment(Element.ALIGN_CENTER);// 居中显示        aTable.setAlignment(Element.ALIGN_MIDDLE);// 纵向居中显示        aTable.setAutoFillEmptyCells(true); // 自动填满        aTable.setBorderWidth(0); // 边框宽度        aTable.setBorderColor(new Color(0, 125, 255)); // 边框颜色        Font fontChinese = new Font(bfChinese, 10, Font.BOLD);        Cell cell11 = new Cell(new Phrase("教学环节", fontChinese));        cell11.setVerticalAlignment(Element.ALIGN_CENTER);        cell11.setHorizontalAlignment(Element.ALIGN_CENTER);        cell11.setColspan(2);        cell11.setBorderColor(new Color(0, 0, 0));        cell11.setBackgroundColor(new Color(153, 204, 255));        aTable.addCell(cell11);        Cell cell12 = new Cell(new Phrase("时间(分钟)", fontChinese));        cell12.setVerticalAlignment(Element.ALIGN_CENTER);        cell12.setHorizontalAlignment(Element.ALIGN_CENTER);        cell12.setRowspan(1);        cell12.setBorderColor(new Color(0, 0, 0));        cell12.setBackgroundColor(new Color(153, 204, 255));        aTable.addCell(cell12);        Cell cell13 = new Cell(new Phrase("教学活动", fontChinese));        cell13.setVerticalAlignment(Element.ALIGN_CENTER);        cell13.setHorizontalAlignment(Element.ALIGN_LEFT);        cell13.setRowspan(1);        cell13.setBorderColor(new Color(0, 0, 0));        cell13.setBackgroundColor(new Color(153, 204, 255));        aTable.addCell(cell13);        Font fontChinesecontent = new Font(bfChinese, 10, Font.BOLD);        Cell cell21 = new Cell(new Phrase("课程引入、学习目标分析", fontChinesecontent));        cell21.setVerticalAlignment(Element.ALIGN_CENTER);        cell21.setHorizontalAlignment(Element.ALIGN_LEFT);        cell21.setColspan(2);        cell21.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell21);        Cell cell22 = new Cell(new Phrase("5", fontChinesecontent));        cell22.setVerticalAlignment(Element.ALIGN_CENTER);        cell22.setHorizontalAlignment(Element.ALIGN_CENTER);        cell22.setRowspan(1);        cell22.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell22);        Cell cell23 = new Cell(new Phrase("教师设问,播放课件,学生讨论", fontChinesecontent));        cell23.setVerticalAlignment(Element.ALIGN_CENTER);        cell23.setHorizontalAlignment(Element.ALIGN_LEFT);        cell23.setRowspan(1);        cell23.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell23);        Cell cell31 = new Cell(new Phrase("新课\n讲解\n技能\n训练", fontChinesecontent));        cell31.setVerticalAlignment(Element.ALIGN_CENTER);        cell31.setHorizontalAlignment(Element.ALIGN_CENTER);        cell31.setRowspan(2);        cell31.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell31);        Cell cell32 = new Cell(new Phrase("???", fontChinesecontent));        cell32.setVerticalAlignment(Element.ALIGN_CENTER);        cell32.setHorizontalAlignment(Element.ALIGN_LEFT);        cell32.setRowspan(1);        cell32.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell32);        Cell cell33 = new Cell(new Phrase("9", fontChinesecontent));        cell33.setVerticalAlignment(Element.ALIGN_CENTER);        cell33.setHorizontalAlignment(Element.ALIGN_CENTER);        cell33.setRowspan(1);        cell33.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell33);        Cell cell34 = new Cell(new Phrase("教师讲解,学生讨论", fontChinesecontent));        cell34.setVerticalAlignment(Element.ALIGN_CENTER);        cell34.setHorizontalAlignment(Element.ALIGN_LEFT);        cell34.setRowspan(1);        cell34.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell34);        Cell cell41 = new Cell(new Phrase("???", fontChinesecontent));        cell41.setVerticalAlignment(Element.ALIGN_CENTER);        cell41.setHorizontalAlignment(Element.ALIGN_LEFT);        cell41.setRowspan(1);        cell41.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell41);        Cell cell42 = new Cell(new Phrase("15", fontChinesecontent));        cell42.setVerticalAlignment(Element.ALIGN_CENTER);        cell42.setHorizontalAlignment(Element.ALIGN_CENTER);        cell42.setRowspan(1);        cell42.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell42);        Cell cell43 = new Cell(new Phrase("???", fontChinesecontent));        cell43.setVerticalAlignment(Element.ALIGN_CENTER);        cell43.setHorizontalAlignment(Element.ALIGN_LEFT);        cell43.setRowspan(1);        cell43.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell43);        Cell cell51 = new Cell(new Phrase("课程小结", fontChinesecontent));        cell51.setVerticalAlignment(Element.ALIGN_CENTER);        cell51.setHorizontalAlignment(Element.ALIGN_LEFT);        cell51.setColspan(2);        cell51.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell51);        Cell cell52 = new Cell(new Phrase("5", fontChinesecontent));        cell52.setVerticalAlignment(Element.ALIGN_CENTER);        cell52.setHorizontalAlignment(Element.ALIGN_CENTER);        cell52.setRowspan(1);        cell52.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell52);        Cell cell53 = new Cell(new Phrase("学生讨论归纳,教师点评", fontChinesecontent));        cell53.setVerticalAlignment(Element.ALIGN_CENTER);        cell53.setHorizontalAlignment(Element.ALIGN_LEFT);        cell53.setRowspan(1);        cell53.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell53);        Cell cell61 = new Cell(new Phrase("过程评价", fontChinesecontent));        cell61.setVerticalAlignment(Element.ALIGN_CENTER);        cell61.setHorizontalAlignment(Element.ALIGN_LEFT);        cell61.setColspan(2);        cell61.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell61);        Cell cell62 = new Cell(new Phrase("3", fontChinesecontent));        cell62.setVerticalAlignment(Element.ALIGN_CENTER);        cell62.setHorizontalAlignment(Element.ALIGN_CENTER);        cell62.setRowspan(1);        cell62.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell62);        Cell cell63 = new Cell(new Phrase("学生自评和互评,教师评价在巡视中完成课堂表现部分,其余在课后补充完整", fontChinesecontent));        cell63.setVerticalAlignment(Element.ALIGN_CENTER);        cell63.setHorizontalAlignment(Element.ALIGN_LEFT);        cell63.setRowspan(1);        cell63.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell63);        Cell cell71 = new Cell(new Phrase("作业布置", fontChinesecontent));        cell71.setVerticalAlignment(Element.ALIGN_CENTER);        cell71.setHorizontalAlignment(Element.ALIGN_LEFT);        cell71.setColspan(2);        cell71.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell71);        Cell cell72 = new Cell(new Phrase("3", fontChinesecontent));        cell72.setVerticalAlignment(Element.ALIGN_CENTER);        cell72.setHorizontalAlignment(Element.ALIGN_CENTER);        cell72.setRowspan(1);        cell72.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell72);        Cell cell73 = new Cell(new Phrase("教师布置课后作业(功能改进),或下发任务单。学生按要求完成", fontChinesecontent));        cell73.setVerticalAlignment(Element.ALIGN_CENTER);        cell73.setHorizontalAlignment(Element.ALIGN_LEFT);        cell73.setRowspan(1);        cell73.setBorderColor(new Color(0, 0, 0));        aTable.addCell(cell73);        document.add(aTable);        document.add(new Paragraph("\n"));    }    /*     * 测试控制清单     * */    public  void insertRiskControlTable() throws DocumentException{        Table aTable = new Table(11,3);        int width[] = { 5, 13, 5, 9, 9, 13, 9, 9, 9, 9, 9 };        aTable.setWidths(width);// 设置每列所占比例        aTable.setWidth(100); // 占页面宽度 90%        aTable.setAlignment(Element.ALIGN_CENTER);// 居中显示        aTable.setAlignment(Element.ALIGN_MIDDLE);// 纵向居中显示        aTable.setAutoFillEmptyCells(true); // 自动填满        aTable.setBorderWidth(0); // 边框宽度        aTable.setBorderColor(new Color(0, 125, 255)); // 边框颜色        Font fontChinese = new Font(bfChinese, 10, Font.BOLD);        Cell cell = new Cell(new Phrase("\n测试代码\n", fontChinese));        cell.setVerticalAlignment(Element.ALIGN_CENTER);        cell.setHorizontalAlignment(Element.ALIGN_CENTER);        cell.setBorderColor(new Color(0, 0, 0));        cell.setBackgroundColor(new Color(204, 153, 255));        aTable.addCell(cell);        Cell cell1 = new Cell(new Phrase("测试名称", fontChinese));        cell1.setVerticalAlignment(Element.ALIGN_CENTER);        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);        cell1.setBorderColor(new Color(0, 0, 0));        cell1.setBackgroundColor(new Color(204, 153, 255));        aTable.addCell(cell1);        Cell cell2 = new Cell(new Phrase("行为代码", fontChinese));        cell2.setVerticalAlignment(Element.ALIGN_CENTER);        cell2.setHorizontalAlignment(Element.ALIGN_CENTER);        cell2.setBorderColor(new Color(0, 0, 0));        cell2.setBackgroundColor(new Color(204, 153, 255));        aTable.addCell(cell2);        Cell cell3 = new Cell(new Phrase("引发测试的行为", fontChinese));        cell3.setVerticalAlignment(Element.ALIGN_CENTER);        cell3.setBorderColor(new Color(0, 0, 0));        cell3.setBackgroundColor(new Color(204, 153, 255));        aTable.addCell(cell3);        Cell cell4 = new Cell(new Phrase("测试控制态度", fontChinese));        cell4.setVerticalAlignment(Element.ALIGN_CENTER);        cell4.setHorizontalAlignment(Element.ALIGN_CENTER);        cell4.setBorderColor(new Color(0, 0, 0));        cell4.setBackgroundColor(new Color(204, 153, 255));        aTable.addCell(cell4);        Cell cell5 = new Cell(new Phrase("控制措施", fontChinese));        cell5.setVerticalAlignment(Element.ALIGN_CENTER);        cell5.setHorizontalAlignment(Element.ALIGN_CENTER);        cell5.setBorderColor(new Color(0, 0, 0));        cell5.setBackgroundColor(new Color(204, 153, 255));        aTable.addCell(cell5);        Cell cell6 = new Cell(new Phrase("措施类型", fontChinese));        cell6.setVerticalAlignment(Element.ALIGN_CENTER);        cell6.setHorizontalAlignment(Element.ALIGN_CENTER);        cell6.setBorderColor(new Color(0, 0, 0));        cell6.setBackgroundColor(new Color(204, 153, 255));        aTable.addCell(cell6);        Cell cell7 = new Cell(new Phrase("完成标志", fontChinese));        cell7.setVerticalAlignment(Element.ALIGN_CENTER);        cell7.setHorizontalAlignment(Element.ALIGN_CENTER);        cell7.setBorderColor(new Color(0, 0, 0));        cell7.setBackgroundColor(new Color(204, 153, 255));        aTable.addCell(cell7);        Cell cell8 = new Cell(new Phrase("控制措施完成时间", fontChinese));        cell8.setVerticalAlignment(Element.ALIGN_CENTER);        cell8.setHorizontalAlignment(Element.ALIGN_CENTER);        cell8.setBorderColor(new Color(0, 0, 0));        cell8.setBackgroundColor(new Color(204, 153, 255));        aTable.addCell(cell8);        Cell cell9 = new Cell(new Phrase("控制措施牵头部门", fontChinese));        cell9.setVerticalAlignment(Element.ALIGN_CENTER);        cell9.setHorizontalAlignment(Element.ALIGN_CENTER);        cell9.setBorderColor(new Color(0, 0, 0));        cell9.setBackgroundColor(new Color(204, 153, 255));        aTable.addCell(cell9);        Cell cell10 = new Cell(new Phrase("控制措施配合部门", fontChinese));        cell10.setVerticalAlignment(Element.ALIGN_CENTER);        cell10.setHorizontalAlignment(Element.ALIGN_CENTER);        cell10.setBorderColor(new Color(0, 0, 0));        cell10.setBackgroundColor(new Color(204, 153, 255));        aTable.addCell(cell10);        for(int i=0;i<22;i++){            aTable.addCell(new Cell(i+""));        }        document.add(aTable);        document.add(new Paragraph("\n"));    }    /**     * @param imgUrl 图片路径     * @param imageAlign 显示位置     * @param height 显示高度     * @param weight 显示宽度     * @param percent 显示比例     * @param heightPercent 显示高度比例     * @param weightPercent 显示宽度比例     * @param rotation 显示图片旋转角度     * @throws MalformedURLException     * @throws IOException     * @throws DocumentException     */    public void insertImg(String imgUrl,int imageAlign,int height,int weight,int percent,int heightPercent,int weightPercent,int rotation) throws MalformedURLException, IOException, DocumentException{//       添加图片        Image img = Image.getInstance(imgUrl);        if(img==null)            return;        img.setAbsolutePosition(0, 0);        img.setAlignment(imageAlign);        img.scaleAbsolute(height, weight);        img.scalePercent(percent);        img.scalePercent(heightPercent, weightPercent);        img.setRotation(rotation);        document.add(img);    }    public void closeDocument() throws DocumentException{        this.document.close();    }    public static void main(String[] args) throws DocumentException, IOException {        GenerateTest wt = new GenerateTest();        wt.openDocument("e:\\domeTest.doc");        wt.insertTitle("面向对象编程基础(Java)教案设计", 18, Font.BOLD, Element.ALIGN_CENTER);        wt.insertTitle("\n", 12, Font.BOLD, Element.ALIGN_LEFT);        wt.insertTitle("吴新星", 10, Font.NORMAL, Element.ALIGN_RIGHT);        wt.insertTitle("2014年10月19日", 10, Font.NORMAL, Element.ALIGN_RIGHT);        wt.insertContext("\t 本次课的教学内容为", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertTitle("\t 一、教学说明", 12, Font.BOLD, Element.ALIGN_LEFT);        wt.insertContext("\t 1、要完成本次课的教学,教师应准备如下材料:", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 教材、进度表、大纲、课表、在线Web资源、多媒体课件、", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 2、学生应具备的基础:", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 1) 完成", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 2) 具备", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 二、教学目的", 12, Font.BOLD, Element.ALIGN_LEFT);        wt.insertContext("\t 通过本次课的学习,要求学生达到以下知识和能力目标。", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 1、知识目标", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 1) 能完全理解", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 2) 能利用所学知识", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 2、能力目标", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 1) 能准确分析", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 3、素质目标", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 1) 具备查阅资料的能力;", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 2) 具备独立工作或团队合作的能力;", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 3) 具备精益求精、严谨求实的工作态度;", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 4) 具备良好的职业道德和素质。", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertTitle("\t 三、教学重点和难点分析", 12, Font.BOLD, Element.ALIGN_LEFT);        wt.insertContext("\t 1、教学重点", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 知识点。", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 2、教学难点", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 知识点。", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertTitle("\t 四、教学思想", 12, Font.BOLD, Element.ALIGN_LEFT);        wt.insertTitle("\t 本次课是上次课的应用和延伸,重在对学生排故能力的训练,需要教师在安装好的电路上预先设置典型故障,让学生通过观察故障现象、分组讨论故障原因和范围,并最终利用万用表排除故障。排故能力的训练,可为后续复杂项目的开展,及今后学生获取维修电工中级职业资格书打好基础。", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 为了巩固知识,在讲授过程中教师要让学生同步完成配套的工作页。", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertTitle("\t 五、教学过程和教学方法设计", 12, Font.BOLD, Element.ALIGN_LEFT);        wt.insertContext("\t 教学过程采用“教学做一体化”的方式开展,辅以多媒体课件、实物操作、Flash动画、分析讨论、习题训练等教学手段。", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 整个教学过程分为以下四个阶段:", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 1、课程引入:", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 2、知识和技能训练:", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 3、课堂操作:", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertContext("\t 4、任务总结、过程评价、作业布置:", 12, Font.NORMAL, Element.ALIGN_LEFT);        wt.insertTitle("\t 五、教学过程和教学方法设计", 12, Font.BOLD, Element.ALIGN_LEFT);//        wt.insertContext("① 部门角度测试分析", 12, Font.NORMAL, Element.ALIGN_LEFT);//        wt.insertImg("test.bmp", Image.ALIGN_CENTER, 12, 35, 50, 50, 50, 30);//        wt.insertContext("② 主体角度测试分析", 12, Font.NORMAL, Element.ALIGN_LEFT);//        wt.insertImg("test.bmp", Image.ALIGN_CENTER, 12, 35, 50, 60, 60, 30);//        wt.insertContext("③ 部门主体交叉角度测试分析", 12, Font.NORMAL, Element.ALIGN_LEFT);//        wt.insertImg("test.bmp", Image.ALIGN_CENTER, 50, 75, 100, 100, 100, 30);//        wt.insertContext("④ 业务活动角度测试分析", 12, Font.NORMAL, Element.ALIGN_LEFT);//        wt.insertImg("test.bmp", Image.ALIGN_CENTER, 12, 35, 50, 80, 80, 30);        wt.insertTitle("二、重大测试清单", 12, Font.BOLD, Element.ALIGN_CENTER);        wt.insertRiskTable();        wt.insertTitle("三、测试控制现状评估结果", 12, Font.BOLD, Element.ALIGN_CENTER);        wt.insertRiskEvaluationTable();        wt.insertTitle("四、测试控制计划", 12, Font.BOLD, Element.ALIGN_CENTER);        wt.insertRiskControlTable();        wt.closeDocument();    }

生成报表

package com.ybzt.views.report;import java.awt.Color;import java.awt.Font;import java.io.File;import java.io.FileOutputStream;import java.text.DecimalFormat;import java.text.NumberFormat;import javax.servlet.http.HttpServletRequest;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartUtilities;import org.jfree.chart.JFreeChart;import org.jfree.chart.labels.StandardPieSectionLabelGenerator;import org.jfree.chart.plot.PiePlot3D;import org.jfree.chart.title.TextTitle;import org.jfree.data.general.DefaultPieDataset;import org.jfree.data.general.PieDataset;import org.springframework.beans.factory.annotation.Autowired;public class CreateChart {     private static  String CHART_PATH = "";     public CreateChart(String path){         this.CHART_PATH = path;     }    private CreateChart() {        // TODO Auto-generated constructor stub    }    /**     * 饼状图     *      * @param dataset 数据集     * @param chartTitle 图标题     * @param charName 生成图的名字     * @param pieKeys 分饼的名字集     * @return     */    public static String createValidityComparePimChar(PieDataset dataset,            String chartTitle, String charName, String[] pieKeys) {        JFreeChart chart = ChartFactory.createPieChart3D(chartTitle, // chart                // title                dataset,// data                true,// include legend                true, false);        // 使下说明标签字体清晰,去锯齿类似于        // chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);的效果        chart.setTextAntiAlias(false);        // 图片背景色        chart.setBackgroundPaint(Color.white);        // 设置图标题的字体重新设置title        Font font = new Font("隶书", Font.BOLD, 25);        TextTitle title = new TextTitle(chartTitle);        title.setFont(font);        chart.setTitle(title);        PiePlot3D plot = (PiePlot3D) chart.getPlot();        // 图片中显示百分比:默认方式        // 指定饼图轮廓线的颜色        // plot.setBaseSectionOutlinePaint(Color.BLACK);        // plot.setBaseSectionPaint(Color.BLACK);        // 设置无数据时的信息        plot.setNoDataMessage("无对应的数据,请重新查询。");        // 设置无数据时的信息显示颜色        plot.setNoDataMessagePaint(Color.red);        // 图片中显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位        plot.setLabelGenerator(new StandardPieSectionLabelGenerator(                "{0}={1}({2})", NumberFormat.getNumberInstance(),                new DecimalFormat("0.00%")));        // 图例显示百分比:自定义方式, {0} 表示选项, {1} 表示数值, {2} 表示所占比例        plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator(                "{0}={1}({2})"));        plot.setLabelFont(new Font("SansSerif", Font.TRUETYPE_FONT, 12));        // 指定图片的透明度(0.0-1.0)        plot.setForegroundAlpha(0.65f);        // 指定显示的饼图上圆形(false)还椭圆形(true)        plot.setCircular(false, true);        // 设置第一个 饼块section 的开始位置,默认是12点钟方向        plot.setStartAngle(90);        // // 设置分饼颜色        plot.setSectionPaint(pieKeys[0], new Color(47, 69, 84));        plot.setSectionPaint(pieKeys[1], new Color(213, 58, 53));        FileOutputStream fos_jpg = null;        try {            // 文件夹不存在则创建//            isChartPathExist(CHART_PATH);//            String chartName = "D:/workspace1/happyReading/src/main/webapp/exportWord/" + charName;            String chartName =  CHART_PATH+ charName;//            System.out.println("charName:"+chartName);            fos_jpg = new FileOutputStream(chartName);            // 高宽的设置影响椭圆饼图的形状            ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 230);            return chartName;        } catch (Exception e) {            e.printStackTrace();            return null;        } finally {            try {                fos_jpg.close();            } catch (Exception e) {                e.printStackTrace();            }        }    }    /**     * 判断文件夹是否存在,如果不存在则新建     * @param chartPath     */    private void isChartPathExist(String chartPath) {        File file = new File("");        String absolutePath = file.getAbsolutePath();        String path =absolutePath+"/chart";        if (!file.exists()) {            file.mkdirs();        // log.info("CHART_PATH="+CHART_PATH+"create.");        }    }       /**     * 生成饼状图     */    public static String makePieChart(String pieName) {        double[] data = {20, 80};        String[] keys = {"未参与人数", "参与人数"};        String createPath = createValidityComparePimChar(getDataPieSetByUtil(data, keys), "饼状图",                pieName, keys);        System.out.println("创建的路劲:"+createPath);        return createPath;    }    // 饼状图 数据集    public static PieDataset getDataPieSetByUtil(double[] data,            String[] datadescription) {        if (data != null && datadescription != null) {            if (data.length == datadescription.length) {                DefaultPieDataset dataset = new DefaultPieDataset();                for (int i = 0; i < data.length; i++) {                    dataset.setValue(datadescription[i], data[i]);                }                return dataset;            }        }        return null;    }    public static void main(String[] args) {        //  Auto-generated method stub        CreateChart pm = new CreateChart();//      pm.getPath();        // 生成饼状图        pm.makePieChart("1.png");//      pm.getPath();        // 生成单组柱状图//        pm.makeBarChart();//        // 生成多组柱状图//        pm.makeBarGroupChart();//        // 生成堆积柱状图//        pm.makeStackedBarChart();//        // 生成折线图//        pm.makeLineAndShapeChart();    }}

需要的jar 包

<!--        java 导出word 依赖 --><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><!-- java 生成报表 --><dependency>    <groupId>org.jfree</groupId>    <artifactId>jfreechart</artifactId>    <version>1.0.19</version></dependency><dependency>    <groupId>org.jfree</groupId>    <artifactId>jfreesvg</artifactId>    <version>3.0</version></dependency><dependency>    <groupId>org.jfree</groupId>    <artifactId>jcommon</artifactId>    <version>1.0.23</version></dependency>

还有一个iTextAsian.jar 因为 5.0 的版本 别名没有改.我也比较懒就没有弄 就把这个jar 复制到lib下面,没有用maven 依赖

目前这个还有一个bug 没有解决 就是用户 几点导出的时,没有实现导出时自己选择下载路劲. 有哪位大神做过的话.可以给我留言.

0 0
原创粉丝点击