今天下午没事,就整合了项目中的导入word文档的代码,因为业务要求要把数据可视化,所以选择了就freechart插件作为画图工具,导入word文档选择的Itext,闲话不多说,直接上代码:

jar包:itext-2.1.7.jar itext-rtf-2.1.7.jar iTextAsian.jar      || jfreechart-1.0.13.jar  jcommon-1.0.15.jar

导出word步骤概括:

1.建立新文档: Document document = new Document(PageSize.A4);

2.开启 书写器:String savePath = "G:/test/testPicture.doc";
 FileOutputStream fos = new FileOutputStream(savePath);
  RtfWriter2.getInstance(document, fos);

3.打开文档:document.open();

4.往文档里添加东西:可以是段落,也可以是图片或表格 document.add(paragraph);

5.关闭文档与流:document.close(); fos.close();

以上就是 导出文档的所有步骤,具体的格式要根据需求去调整了

直接上代码:

ChartUtil:生成相应的 chart 图表

package com.util.export.word;import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.List;import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.DateTickUnitType;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RectangleEdge;
import org.jfree.util.Rotation;import com.lowagie.text.Rectangle;/*** JfreeChart * 2017-05-12* @author zqz **/
public class ChartUtil {/*** 饼图* @param title 图表题* @param dataset 数据源* @param legend 图例* @param tooltips 提示* @param locale 是否指定URL* @return*/public static JFreeChart getPieChart(String title,DefaultPieDataset dataset,boolean legend,boolean tooltips,boolean locale,RectangleEdge r){ChartFactory.setChartTheme(getChartTheme());   //title:图表题; dataset:数据源; legend:是否显示图例;tooltips:是否显示tooltip;locale:是否指定urlJFreeChart chart=ChartFactory.createPieChart3D(title, dataset, legend, tooltips, locale);//设置图标样式setChart(chart);//图例样式setLegendTitle(chart,r);//得到饼图的plot对象PiePlot3D plot = (PiePlot3D) chart.getPlot();//设置旋转角度    plot.setStartAngle(180.0);    //设置旋转方向,Rotation.CLOCKWISE)为顺时针。    plot.setDirection(Rotation.CLOCKWISE);    //设置图表透明图0.0~1.0范围。0.0为完全透明,1.0为完全不透明。    plot.setForegroundAlpha(0.5F);    // plot.setNoDataMessage("无数据");    //扇区标签setLabel(plot);//扇区颜色setSection(plot,dataset);return chart;}/*** 柱状图* @param dataset 数据集* @param isSingle * @param barColor 柱颜色* @return*/public static JFreeChart getBarChart(String title,CategoryDataset dataset,boolean isSingle,PlotOrientation p,Color barColor,CategoryLabelPositions c,RectangleEdge r){ChartFactory.setChartTheme(getChartTheme());JFreeChart chart=null; if(isSingle){chart = ChartFactory.createBarChart3D(title, "", "", dataset, p, false,false, false);}else{chart = ChartFactory.createStackedBarChart3D(title, "", "",dataset,p, false,false, false);}setChart(chart);//图形的绘制结构对象CategoryPlot plot = (CategoryPlot) chart.getPlot();setPlot(plot);     //设置x轴样式setAxis(plot,c);//设置y轴样式setValueAxis(plot);//设置图例setLegendTitle(chart,r);//设置y轴刻度setNumberAxis(plot, false);//设置BarsetBar(plot, isSingle, dataset, barColor);return chart;}public static JFreeChart getMultiBarChart(String title,CategoryDataset dataset,CategoryLabelPositions c,int paint,RectangleEdge r){ChartFactory.setChartTheme(getChartTheme());JFreeChart chart = ChartFactory.createBarChart(title,// 标题"",// x轴"",// y轴dataset,// 数据PlotOrientation.VERTICAL,// 定位,VERTICAL:垂直false,// 是否显示图例注释(对于简单的柱状图必须是false)false,// 是否生成工具//没用过false);// 是否生成URL链接//没用过setChart(chart);//图形的绘制结构对象CategoryPlot plot = (CategoryPlot) chart.getPlot();setPlot(plot);        //设置x轴样式setAxis(plot,c);//设置y轴样式setValueAxis(plot);//设置图例setLegendTitle(chart,r);//设置y轴刻度setNumberAxis(plot, false);//设置BarsetRender(plot,paint);return chart;}public static void setRender(CategoryPlot plot,int paint){BarRenderer renderer1 = new BarRenderer();// 设置柱子的相关属性renderer1.setMinimumBarLength(0.5);renderer1.setItemMargin(0.2);// renderer1.set// 是否显示阴影renderer1.setShadowVisible(false);plot.setRenderer(renderer1);plot.setBackgroundAlpha((float) 0.1); // 数据区的背景透明度(0.0~1.0)renderer1.setSeriesPaint(0,new Color(74,126,187));if(paint==1){renderer1.setSeriesPaint(1,new Color(190, 75, 72));}if(paint==2){renderer1.setSeriesPaint(1,new Color(190, 75, 72));renderer1.setSeriesPaint(2, new Color(152, 185, 84));  }}/*** 折线图* @param dataset 数据集* @param numberAxis y轴精度* @param isGroup * @return*/public static JFreeChart getLineChart(String title,DefaultCategoryDataset dataset,boolean numberAxis,boolean isGroup,CategoryLabelPositions c,RectangleEdge r){ChartFactory.setChartTheme(getChartTheme());JFreeChart chart=ChartFactory.createLineChart(title, "", "", dataset, PlotOrientation.VERTICAL, false,true,false);setChart(chart);//图形的绘制结构对象CategoryPlot plot = chart.getCategoryPlot();setPlot(plot);//设置x轴setAxis(plot,c);      //设置y轴setValueAxis(plot);//设置y轴刻度显示样式setNumberAxis(plot, numberAxis);//设置折线样式setRender(plot, isGroup);//设置图例setLegendTitle(chart,r);return chart;       }/*** 设置网格* @param plot*/public static void setPlot(CategoryPlot plot){//设置网格背景色plot.setBackgroundPaint(Color.WHITE);//设置网格竖线颜色plot.setDomainGridlinePaint(Color.WHITE);//设置网格横线颜色plot.setRangeGridlinePaint(Color.BLACK);//设置数据区的边界线条颜色plot.setOutlinePaint(Color.WHITE);}/*** 设置y轴刻度显示样式* @param plot* @param numberAxis*/public static void setNumberAxis(CategoryPlot plot,boolean numberAxis){Font kfont=new Font("宋体", Font.PLAIN, 12);NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();String numAxis="#0";if(numberAxis||numberaxis.getUpperBound()<=6){//y轴显示精度numAxis="#0.00";}numberaxis.setNumberFormatOverride(new DecimalFormat(numAxis));numberaxis.setTickLabelFont(kfont);  }/***  获得renderer 注意这里是下嗍造型到lineandshaperenderer!!  * @param plot*/public static void setRender(CategoryPlot plot,boolean isGroup){LineAndShapeRenderer renderer=(LineAndShapeRenderer)plot.getRenderer();//显示折点数据renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());// 定义series为"First"的(即series1)点之间的连线// 第几个数据集 ; 线的宽度 ; 控制虚线直线renderer.setSeriesStroke( 0, new BasicStroke(3.0F,1, 1, 1.0F, new float[] { 10F,0F }, 1F));//设置颜色renderer.setSeriesPaint(0,new Color(74,126,187));if(isGroup){renderer.setSeriesPaint(1,new Color(190, 75, 72));renderer.setSeriesPaint(2, new Color(152, 185, 84));renderer.setSeriesStroke(1, new BasicStroke(3.0F,1, 1, 1.0F, new float[] { 10F, 0F }, 1F));renderer.setSeriesStroke(2, new BasicStroke(3.0F,1, 1, 1.0F, new float[] { 10F, 0F }, 1F));} }/*** 设置x轴*/public static void setAxis(CategoryPlot plot,CategoryLabelPositions c){// 配置字体  Font xfont = new Font("宋体", Font.PLAIN, 12);// X轴  //X轴  CategoryAxis domainAxis = plot.getDomainAxis();//x轴的标题文字是否显示domainAxis.setTickLabelsVisible(true);//设置x轴标题字体domainAxis.setLabelFont(xfont);//设置x轴字体domainAxis.setTickLabelFont(xfont);//设置字体颜色domainAxis.setTickLabelPaint(Color.BLACK);//x轴label斜显示domainAxis.setCategoryLabelPositions(c);//分类轴编剧,同种类型之间的距离domainAxis.setCategoryMargin(0);//分类轴下(左)边距,就是离左边的距离  domainAxis.setLowerMargin(0.1);  //分类轴下(右)边距,就是离最右边的距离  domainAxis.setUpperMargin(0.1); }/*** 自定义x轴时间刻度* @return*/public static JFreeChart createChart(String title,int unit,TimeSeriesCollection dataset,RectangleEdge rs){ChartFactory.setChartTheme(getChartTheme());  JFreeChart jFreeChart=ChartFactory.createTimeSeriesChart(title,//图表名"",//横轴标签文字"",//纵轴标签文字dataset,//图表的数据集合true,//是否显示图表中每条数据序列的说明false,//是否显示工具提示false);//是否显示图表中设置的url网络连接//XYPlot图表区域的设置对象,用来设置图表的一些显示属性XYPlot xyPlot=(XYPlot)jFreeChart.getPlot();setXYPlot(xyPlot);setXYValueAxis(xyPlot);setDateAxis(xyPlot, unit);setChart(jFreeChart);//设置图例setLegendTitle(jFreeChart,rs);return jFreeChart;}/*** 设置时序图Axis*/public static void setDateAxis(XYPlot xyPlot,int unit){//DateAxis是显示样式设置对象DateAxis dateAxis=(DateAxis) xyPlot.getDomainAxis();SimpleDateFormat frm=new SimpleDateFormat("yyyy年MM月dd日");//设置时间间隔为1天dateAxis.setTickUnit(new DateTickUnit(DateTickUnitType.DAY,unit, frm));// 配置字体  Font xfont = new Font("宋体", Font.PLAIN, 10);// X轴  //x轴的标题文字是否显示dateAxis.setTickLabelsVisible(true);// dateAxis.setAutoTickUnitSelection(true);//设置x轴标题字体 dateAxis.setLabelFont(xfont);// dateAxis.setVerticalTickLabels(true);//设置x轴字体dateAxis.setTickLabelFont(xfont);dateAxis.setDateFormatOverride(new SimpleDateFormat("MM.dd"));      //设置字体颜色// ((CategoryAxis) dateAxis).setCategoryLabelPositions(c);//分类轴编剧,同种类型之间的距离//  dateAxis.setCategoryMargin(0);//分类轴下(左)边距,就是离左边的距离  //dateAxis.setLowerMargin(0.1);  //分类轴下(右)边距,就是离最右边的距离  dateAxis.setUpperMargin(0.1); dateAxis.setAutoRange(true);}/*** 设置时序图*/public static void setXYPlot(XYPlot plot){//设置网格背景色plot.setBackgroundPaint(Color.WHITE);//设置网格竖线颜色plot.setDomainGridlinePaint(Color.WHITE);//设置网格横线颜色plot.setRangeGridlinePaint(Color.BLACK);//设置数据区的边界线条颜色plot.setOutlinePaint(Color.WHITE);XYItemRenderer r = plot.getRenderer();if (r instanceof XYLineAndShapeRenderer) {XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;renderer.setBaseShapesVisible(true);renderer.setBaseShapesFilled(false);}}/*** 设置y轴*/public static void setXYValueAxis(XYPlot plot){// 配置字体  Font yfont = new Font("宋体", Font.CENTER_BASELINE, 20);// Y轴       //y轴ValueAxis rangeAxis=plot.getRangeAxis();rangeAxis.setAutoRange(true);//隐藏y轴的刻度标签rangeAxis.setTickLabelsVisible(true);//设置Y轴标题字体rangeAxis.setLabelFont(yfont); //标记线是否显示rangeAxis.setMinorTickMarksVisible(false);//设置y轴字体角度(1.6的时候是水平)rangeAxis.setLabelAngle(1.6);//设置字体颜色rangeAxis.setLabelPaint(Color.BLACK);rangeAxis.setLowerBound(0);Font kfont=new Font("宋体", Font.PLAIN, 12);  NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();String numAxis="#0";if(numberaxis.getUpperBound()<=6){//y轴显示精度numAxis="#0.00";}numberaxis.setNumberFormatOverride(new DecimalFormat(numAxis));numberaxis.setTickLabelFont(kfont);   }/*** 设置y轴*/public static void setValueAxis(CategoryPlot plot){// 配置字体  Font yfont = new Font("宋体", Font.CENTER_BASELINE, 20);// Y轴       //y轴ValueAxis rangeAxis=plot.getRangeAxis();//隐藏y轴的刻度标签rangeAxis.setTickLabelsVisible(true);//设置Y轴标题字体rangeAxis.setLabelFont(yfont); //标记线是否显示rangeAxis.setMinorTickMarksVisible(false);//设置y轴字体角度(1.6的时候是水平)rangeAxis.setLabelAngle(1.6);//设置字体颜色rangeAxis.setLabelPaint(Color.BLACK);rangeAxis.setLowerBound(0);}/*** 设置Bar*/public static void setBar(CategoryPlot plot,boolean isSingle,CategoryDataset dataset,Color barColor){BarRenderer renderer=(BarRenderer) plot.getRenderer();//设置Bar的颜色//设置每个Bar之间的间隔renderer.setItemMargin(0.1f);//设置每个Bar的最大宽度renderer.setMaximumBarWidth(0.05f);//设置Bar是否显示阴影renderer.setShadowVisible(false);if(isSingle){for(int i=0;i<dataset.getRowKeys().size();i++){renderer.setSeriesPaint(i, barColor);}}} /*** 设置扇区颜色* @param plot*/public static void setSection(PiePlot3D plot,DefaultPieDataset dataset){if (dataset != null) {List<String> list = dataset.getKeys();for (String str : list) {if (str.equals("违法行为"))plot.setSectionPaint("违法行为", new Color(255, 0, 0));if (str.equals("违规行为"))plot.setSectionPaint("违规行为", new Color(255, 165, 0));if (str.equals("不明确行为"))plot.setSectionPaint("不明确行为", new Color(188, 238, 104));if (str.equals("常规行为"))plot.setSectionPaint("常规行为", new Color(67, 205, 128));if (str.equals("无数据")){plot.setSectionPaint("无数据", Color.WHITE);plot.setLabelGenerator(null);}  }}      }//设置图标样式public static void setChart(JFreeChart chart){//设置字体清晰chart.setTextAntiAlias(false);//图片背景色chart.setBackgroundPaint(Color.white);//边界线条是否可见chart.setBorderVisible(true);//边界线条笔触chart.setBorderStroke(new BasicStroke(0.2f));}/*** 设置扇区标签格式* @param plot*/public static void setLabel(PiePlot3D plot){//设置扇区标签显示格式 {0}:关键字 ;{1}:数值;{2}:百分比plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{1},{2}",NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));//设置扇区标签颜色  // plot.setLabelBackgroundPaint(new Color(220, 220, 220)); //设置扇区标签字体plot.setLabelFont(new Font("宋体",Font.PLAIN,10));//设置扇区透明度(0.0-1.0)plot.setForegroundAlpha(1f);//饼图是否一定是正圆plot.setCircular(true);    //设置扇区背景颜色plot.setBackgroundPaint(Color.WHITE);//设置绘图面板外边的填充颜色plot.setOutlinePaint(Color.WHITE);//设置绘图面板阴影的填充色plot.setShadowPaint(Color.WHITE);}/*** 设置图例* @param chart*/public static void setLegendTitle(JFreeChart chart,RectangleEdge r ){Font kfont=new Font("宋体", Font.PLAIN, 12);LegendTitle legendTitle=new LegendTitle(chart.getPlot());//设置四周的边距legendTitle.setBorder(0,0,0,0);//设置图例位置legendTitle.setPosition(r);//设置外边距legendTitle.setMargin(5,5,5,5);//设置字体样式legendTitle.setItemFont(kfont);//移除默认的legendchart.removeLegend();//添加图例chart.addLegend(legendTitle);}/*** 生成饼图图片* @param dataset 数据集* @param url  图片存储路径* @param width 图片宽度* @param height 图片高度*/public static void getPieChartImage(DefaultPieDataset dataset,String url,int width,int height,RectangleEdge r){JFreeChart chart=getPieChart("",dataset,true,true,false,r);FileOutputStream fos_jpg=null;try {fos_jpg=new FileOutputStream(url);ChartUtilities.writeChartAsPNG(fos_jpg,chart,width,height);fos_jpg.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {fos_jpg.close();} catch (IOException e) {e.printStackTrace();}}  }/*** 生成柱状图图片* @param dataset 数据集* @param url 图片存储路径* @param width 图片宽度* @param height 图片高度* @param isSingle 是否单数值显示* @param barColor 柱子颜色*/public static void getBarChartImages(String title,CategoryDataset dataset,String url, int width,int height,PlotOrientation p,boolean isSingle,Color barColor,CategoryLabelPositions c,RectangleEdge r){JFreeChart chart=getBarChart(title,dataset,isSingle,p,barColor,c,r);FileOutputStream fos_jpg=null;try {fos_jpg=new FileOutputStream(url);ChartUtilities.writeChartAsJPEG(fos_jpg,1f,chart,width,height,null);fos_jpg.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {fos_jpg.close();} catch (IOException e) {e.printStackTrace();}}}/*** 多柱图* @param title* @param dataset* @param url* @param width* @param height* @param p* @param paint* @param c* @param r*/public static void getMultiBarChartImages(String title,CategoryDataset dataset,String url, int width,int height,PlotOrientation p,int paint,CategoryLabelPositions c,RectangleEdge r){JFreeChart chart=getMultiBarChart(title,dataset, c,paint,r);FileOutputStream fos_jpg=null;try {fos_jpg=new FileOutputStream(url);ChartUtilities.writeChartAsJPEG(fos_jpg,1f,chart,width,height,null);fos_jpg.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {fos_jpg.close();} catch (IOException e) {e.printStackTrace();}}}/*** 生成折线图图片* @param url 保存路径* @param dataset 数据集* @param isGroup * @param numberAxis* @param width 图片宽度* @param height 图片高度*/public static void getLineChartImages(String title,String url,DefaultCategoryDataset dataset, boolean isGroup, boolean numberAxis,int width,int height,CategoryLabelPositions c,RectangleEdge r){JFreeChart chart=getLineChart(title,dataset, numberAxis, isGroup,c,r);FileOutputStream fos=null;try {    fos=new FileOutputStream(url);ChartUtilities.writeChartAsPNG(fos, chart, width, height);fos.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {fos.close();} catch (IOException e) {e.printStackTrace();}}   }/*** 生成时间轴图* @param url 保存路径* @param dataset 数据集* @param isGroup * @param numberAxis* @param width 图片宽度* @param height 图片高度*/public static void getTimerChartImages(String title,String url,TimeSeriesCollection dataset, boolean isGroup, boolean numberAxis,int width,int height,int unit,RectangleEdge r){//JFreeChart chart=getLineChart(title,dataset, numberAxis, isGroup,c,r);JFreeChart chart=createChart(title, unit,dataset, r);FileOutputStream fos=null;try {  fos=new FileOutputStream(url);ChartUtilities.writeChartAsPNG(fos, chart, width, height);fos.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {fos.close();} catch (IOException e) {e.printStackTrace();}}   }/*** 删除图片* @param imgName*/public static void deleteImg(String imgName){File img=null;try {img=new File(imgName);boolean b=img.exists();if(b){img.delete();}} catch (Exception e) {e.printStackTrace();}}/*** 创建主题样式* @return*/public static StandardChartTheme getChartTheme(){// 创建主题样式StandardChartTheme standardChartTheme = new StandardChartTheme("CN");//设置标题字体  standardChartTheme.setExtraLargeFont(new Font("宋体",Font.PLAIN,20)); return standardChartTheme;}}

WordUtil:集成Jfreechart

package com.util.export.word;import java.awt.Color;
import java.io.IOException;
import java.net.MalformedURLException;import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RectangleEdge;import com.lowagie.text.BadElementException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
/*** * @author zqz**/
public class WordUtil {/*** 插入段落* @param content 段落内容* @param position 段落位置* @param font  字体* @param document* @throws DocumentException*/public static void setparagraph(String content,int position,Font font,int space,Document document) throws DocumentException{//行距Paragraph paragraph=new Paragraph(space);//段落内容paragraph.add(content);//段落位置paragraph.setAlignment(position);//设置字体paragraph.setFont(font);//设置段落前后间距    document.add(paragraph);}/*** 插入图片饼图* @throws IOException * @throws MalformedURLException * @throws BadElementException */public static void setPieImage(String path,DefaultPieDataset  dpd,int width,int height,Document document,RectangleEdge r) {ChartUtil.getPieChartImage(dpd,path, width, height,r);Image pieChart=null;try {pieChart = Image.getInstance(path);document.add(pieChart);ChartUtil.deleteImg(path);} catch (BadElementException | IOException e) {e.printStackTrace();} catch (DocumentException e) {e.printStackTrace();}  }/*** 柱状图* @param path* @param dcd* @param width* @param height* @param single* @param color* @param document*/public static void setBarImage(String title,String path,DefaultCategoryDataset  dcd,PlotOrientation p,int width,int height,boolean single,Color color,Document document,CategoryLabelPositions c,RectangleEdge r) {ChartUtil.getBarChartImages(title,dcd,path,width,height,p,single,color,c,r);Image barChart=null;try {barChart = Image.getInstance(path);document.add(barChart);ChartUtil.deleteImg(path);} catch (BadElementException | IOException e) {e.printStackTrace();} catch (DocumentException e) {e.printStackTrace();}  }/*** 柱状图* @param path* @param dcd* @param width* @param height* @param single* @param color* @param document*/public static void setMultiBarImage(String title,String path,DefaultCategoryDataset  dcd,PlotOrientation p,int width,int height,int paint,Color color,Document document,CategoryLabelPositions c,RectangleEdge r) {ChartUtil.getMultiBarChartImages(title,dcd, path, width, height, p, paint,c,r);Image barChart=null;try {barChart = Image.getInstance(path);document.add(barChart);ChartUtil.deleteImg(path);} catch (BadElementException | IOException e) {e.printStackTrace();} catch (DocumentException e) {e.printStackTrace();}   }/*** 折线图* @param path* @param dcd* @param isGroup* @param numberAxis* @param width* @param height* @param c* @param document*/public static void setLineImage(String title,String path,DefaultCategoryDataset dcd,boolean isGroup, boolean numberAxis, int width, int height, CategoryLabelPositions c,Document document,RectangleEdge r){ChartUtil.getLineChartImages(title,path,dcd, isGroup, numberAxis, width, height, c,r);Image lineChart=null;  try {lineChart=Image.getInstance(path);document.add(lineChart);ChartUtil.deleteImg(path);} catch (DocumentException e) {e.printStackTrace();} catch (MalformedURLException e) {     e.printStackTrace();} catch (IOException e) {       e.printStackTrace();}}/*** 时间轴图* @param title* @param path* @param dcd* @param isGroup* @param numberAxis* @param width* @param height* @param c* @param document* @param r*/public static void setTimerImage(String title,String path,TimeSeriesCollection dataset,boolean isGroup, boolean numberAxis, int width, int height, int unit,Document document,RectangleEdge r){//ChartUtil.getLineChartImages(title,path,dcd, isGroup, numberAxis, width, height, c,r);ChartUtil.getTimerChartImages(title, path, dataset, isGroup, numberAxis, width, height,unit, r);Image lineChart=null;   try {lineChart=Image.getInstance(path);document.add(lineChart);ChartUtil.deleteImg(path);} catch (DocumentException e) {e.printStackTrace();} catch (MalformedURLException e) {     e.printStackTrace();} catch (IOException e) {       e.printStackTrace();}}/*** 设置图片底部提示* @param paragraph* @param imageText* @param bfChinese* @param document* @throws DocumentException*/public static void setImageText(Paragraph paragraph,String imageText,BaseFont bfChinese,Document document) throws DocumentException{paragraph=new Paragraph(imageText);paragraph.setAlignment(Element.ALIGN_CENTER);paragraph.setFont(new Font(bfChinese, 12, Font.NORMAL));document.add(paragraph);     }}

WraperDataUtil:数据类型转化工具类,即 把数据库中的数据转化成图表需要的格式,如 dataset

package com.util.export.word;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;import javax.swing.text.DateFormatter;import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;/*** 数据类型 转化类* * 把 常用的数据类型 封装成 jfreechart - dataset* @author Administrator**/
public class WraperDataUtil {/*** 格式化数据为饼图数据源* @param map* @return*/public static DefaultPieDataset formatPieDpd(Map<String,Long> map){DefaultPieDataset dpd = new DefaultPieDataset();if(map.isEmpty()){dpd.setValue("无数据",0.001);return dpd;}Iterator<?> iter=map.keySet().iterator();while(iter.hasNext()){  String key=(String) iter.next();if(key==null||"".equals(key))continue;dpd.setValue(key,map.get(key));}  return dpd;}/*** 格式化数据为柱状图数据源* @param map* @return */public static DefaultCategoryDataset formatBarDcd(Map<String,Long> map,String legend){Iterator<?> iter=map.keySet().iterator();DefaultCategoryDataset dcd = new DefaultCategoryDataset();while(iter.hasNext()){String key=(String) iter.next();if(key!=null&&!key.equals("")){dcd.addValue(map.get(key),legend,key);}} return dcd;}/*** 时间序列图 转化,此时 为 一条线* 多线 增加TimeSeries* @param field* @param map* @return*/public static TimeSeriesCollection timeData (String field,Map<String, String> map){Iterator<?> iter=map.keySet().iterator();TimeSeriesCollection dataset=new TimeSeriesCollection();TimeSeries s1=new TimeSeries(field,Day.class);while(iter.hasNext()){String key=(String) iter.next();Date x = null;String type ="yyyy-MM-dd";if(key!=null&&!key.equals("")){x= getDataByStr(key,type);s1.addOrUpdate(new Day(x),Double.parseDouble(map.get(key)));}}  dataset.addSeries(s1);return dataset;}/*** 转化时间* @param timeStr* @param type* @return*/public static Date getDataByStr(String timeStr, String type){SimpleDateFormat sdf = new SimpleDateFormat(type);Date date = null;try {date = sdf.parse(timeStr);} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}return date;}
}

测试类:

package com.util.export.word;import java.awt.Color;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RectangleEdge;import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;public class TestWord {public static void main(String[] args) throws Exception {// 模拟数据库 数据Map<String,Long> mapPieOrBar = new HashMap<String, Long>();mapPieOrBar.put("类型A", 111L);mapPieOrBar.put("类型B", 88L);mapPieOrBar.put("类型C", 211L);Map<String,String> mapTime = new HashMap<String, String>();mapTime.put("2017-01-01", "10");mapTime.put("2017-01-02", "30");mapTime.put("2017-01-03", "20");// 开始 写wordDocument document = new Document(PageSize.A4);String savePath = "G:/test/testPicture.doc";FileOutputStream fos = new FileOutputStream(savePath);RtfWriter2.getInstance(document, fos);document.open();//字体样式BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);BaseFont bfHei = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);Font font = new Font(bfHei, 27,Font.BOLD);Font titleFont=new Font(bfChinese,18,Font.BOLD);Font titleTwoFont=new Font(bfChinese,16,Font.BOLD);Font titleThreeFont=new Font(bfChinese,12,Font.NORMAL);Font contentFont=new Font(bfChinese,14,Font.NORMAL);Font imageTextFont=new Font(bfChinese,12,Font.NORMAL);//段落位置int left=Element.ALIGN_LEFT;int center=Element.ALIGN_CENTER;////数据源DefaultCategoryDataset dcd = null;//饼图数据源DefaultPieDataset dpd = null; //标题String title="";//内容String content="";//map接受数据Map<String,Long> map=null;//图片名称String image="";//图片图示信息String imageText="";//设置报表头//设置报表头 大标题title="\n\n\n\n\n\n河南省夏邑县刘店集乡";WordUtil.setparagraph(title,center,font,30,document);//设置报表头 副标题title="李子园村报告\n\n\n";WordUtil.setparagraph(title,center,font,30, document);String rootPath = "G:/test/";dpd = WraperDataUtil.formatPieDpd(mapPieOrBar);image = rootPath+UUID.randomUUID()+".png";WordUtil.setPieImage(image, dpd, 430, 230, document, RectangleEdge.RIGHT);TimeSeriesCollection timeData = WraperDataUtil.timeData("报销", mapTime);image = rootPath+UUID.randomUUID()+".png";WordUtil.setTimerImage("报销查看", image, timeData,true,false,470,260,1, document,RectangleEdge.RIGHT);image = rootPath+UUID.randomUUID()+".png";DefaultCategoryDataset barData = WraperDataUtil.formatBarDcd(mapPieOrBar, "消费");WordUtil.setBarImage("条形图",image,barData,PlotOrientation.VERTICAL, 430,230,true,new Color(79,129,190), document,CategoryLabelPositions.UP_45,RectangleEdge.RIGHT);// document.close();fos.close();}
}

ps:测试执行没有问题,其中我只写了 饼形图,时间序列图,柱形图(条形图)三种图形的测试,由于篇幅太大 其他的不在写了,方式雷同

不足之处,欢迎指正!

Java Itext+jfreehart 导入含有图形的word文档相关推荐

  1. java 多文字水印_Java 如何给Word文档添加多行文字水印

    前言html 我在以往的文章中曾介绍过如何给Word文档添加文本水印和图片水印,及怎样删除文档中的水印.关于文本水印,以前那篇教程里主要指的是单行字体的水印,而在操做Word文档时,有时也会碰到须要添 ...

  2. Java Web项目中使用Freemarker生成Word文档

    Web项目中生成Word文档的操作屡见不鲜,基于Java的解决方案也是很多的,包括使用Jacob.Apache POI.Java2Word.iText等各种方式,其实在从Office 2003开始,就 ...

  3. java实现导出内容不固定的word文档

    之前遇到过一个需求,需要导出一个word的周报,周报的内容是可变,然后网上找了下方法,下面摘抄一种方便的实现手段: Java用freemarker导出word 一.模板的制作 先用Word做一个模板, ...

  4. java设置页码_Java 添加页码到Word文档

    前言 在操作Word文档时,可以通过添加页码来使其条理清晰,以便于后期查看整理.通常来说,一个Word文档包含了多个节,我们可以忽视这些节为整个文档添加连续页码,同时也可以根据不同节来设置不连续页码. ...

  5. java 将ftl文件作为模板导出word文档

    因为poi等输出word很麻烦,所以本文使用word编辑好模板,转成xml再转成ftl,在java中导入ftl模板,填充数据再生成为word下载或保存. 一.模板文档 1.在Word中编辑好word模 ...

  6. doc转pdf java不失真_java使用Aspose实现 word文档转pdf文件高效不失真

    java使用Aspose word文档转pdf功能实现 主要步骤 使用Aspose进行文档转换,首先引入相应的jar包到系统环境 项目resource下导入license.xml文件 使用Aspose ...

  7. word中添加java代码怎么写_Java如何在word文档中写一个段落?

    在Java编程中,如何在word文档中写一个段落? 注意:需要访问网址:http://poi.apache.org/download.html , 下载一个Apache POI软件包.这里下载最新版本 ...

  8. iText创建一个含有中文的pdf文档

    有朋友问我pdfbox支不支持向pdf文档中写入中文.然后试了好多遍都是有乱码,也找了好多资料没有找到解决办法. 但是在查找资料的过程中发现了另一个处理pdf的开源库iText.官方介绍 http:/ ...

  9. java打印word_Java jacob调用打印机打印word文档

    前面说了Java如何生成复杂的Word文档,今年记录下Java如何调用打印机打印word文档. 起初用的是自带的PrintJob,但是系统提供的打印机制并不成熟完整.网上的代码也是千篇一律,在我的打印 ...

最新文章

  1. Spring Boot 整合 Quartz 实现 Java 定时任务的动态配置
  2. delphi如何让程序最小化到任务栏(使用Shell_NotifyIcon API函数)
  3. Linux学习之系统编程篇:IPC 和管道的基本概念及管道的创建
  4. version robot
  5. MyBatis 如何传递参数(全)
  6. Java什么时候提高境界支持async/await写法啊?
  7. WDS部署服务之五高级功能
  8. 【复赛前排分享(一)】上分有路勤为径,大神教你剖析提分点
  9. PMOS做固态继电器,PMOS做高侧双向开关电路,PMOS防电流倒灌电路,PMOS电源防反接电路
  10. select在各个浏览器中的兼容性问题
  11. iOS第三方开源库的吐槽和备忘
  12. cmd批量修改文件名 增加文字_[Windows应用技巧][cmd篇][批量更改文件名]
  13. 【长期更新】Linux学习笔记
  14. php返回token什么意思,token什么意思
  15. 正定矩阵、二次型与椭圆椭球
  16. DELL服务器bios文件编辑,BIOS维修网站www.biosrepair.com-DELL 1600SC服务器BIOS分离过程...
  17. 关于七牛云上传图片的总结
  18. S-SDLC(Secure Software Development Lifecycle) 安全编码规范
  19. 打造你的“私人空间”,玩客云详细评测
  20. speedoffice(Excel)如何让图片随单元格大小改变?

热门文章

  1. 模糊数学Fuzzy Set第2讲——Fuzzy Logic Fuzzy Reasoning
  2. 【转】MEGA构建系统进化树的步骤(以MEGA7为例)
  3. DELL r340服务器U盘安装Centos7
  4. 学习突围5 - 关于计划
  5. CircleImageView用法及源码解析(雷惊风)
  6. C语言做的猜数字小游戏
  7. Android移动开发-Android设备利用光线传感器监测光照强度的实现
  8. 使用pyinstaller打包.py文件生成.exe文件
  9. python爬取小说并下载_python3爬取小说存为文本实现小说下载
  10. 一墙之隔-看向世界和直面速度与激情