Java 下载Word文档xwpfTemplate

Java 下载Word文档xwpfTemplate

文档下载(图片,数据表格),pom依赖

        <dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.15</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.15</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.15</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.4</version></dependency><dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.0.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.8</version></dependency><dependency><groupId>jfree</groupId><artifactId>jfreechart</artifactId><version>1.0.13</version></dependency><dependency><groupId>jfree</groupId><artifactId>jcommon</artifactId><version>1.0.16</version></dependency>

文档生成工具类

package com.ruoyi.common.utils.work;import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureRenderData;
import com.ruoyi.common.utils.DateUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.util.*;public class WordServiceUtils {private static final String SEPARATER = "test";private static final Logger LOGGER = LoggerFactory.getLogger(WordServiceUtils.class);/*** @param data         :需要替换的模板中的变量键值对* @param TemplatePath :word模板在项目中的路径* @param pictureTag   :要替换为图片的变量名* @param wordName     :生成的word名称* @param request* @param response* @throws IOException*/public static String downWord(Map<String, Object> data, String TemplatePath, List<String> pictureTag, String wordName,List<List<Map<String, Object>>> list,HttpServletRequest request, HttpServletResponse response) throws IOException {LOGGER.info("需要替换的模板中的变量键值对:" + data);LOGGER.info("word模板在项目中的路径:" + TemplatePath);
//        处理图片
//        PictureRenderData pictureRenderData = new PictureRenderData(100, 120, data.get("img1").toString());
//        data.put("image", pictureRenderData);
//        LOGGER.info("本地图片" + pictureRenderData);//处理多张图片if (null != pictureTag && pictureTag.size() > 0) {for (int i = 0; i < pictureTag.size(); i++) {//设置Word页面显示的大小PictureRenderData pictureRenderData = new PictureRenderData(400, 300, pictureTag.get(i).toString());data.put("img" + (i + 1), pictureRenderData);LOGGER.info("本地图片:" + pictureRenderData + ",这是第" + (i + 1) + ",张图片");}}String path = WordServiceUtils.class.getClassLoader().getResource("word.docx").getPath();LOGGER.info("获取到的模板路径:path=" + path);File file = new File(path);LOGGER.info("输出结果获取到的路径:file=" + file);XWPFTemplate xwpfTemplate = XWPFTemplate.compile(file);LOGGER.info("获取到文件:xwpfTemplate=" + xwpfTemplate);// 在controller中处理图片,这里进行多张图片处理方法
//      Configure config = xwpfTemplate.getConfig();
//      for (String tag:pictureTag
//      ) {//          config.customPolicy(tag,new PictureRenderPolicy());
//      }LOGGER.info("模板填充数据.");xwpfTemplate.render(data);String docName = "D:\\test\\" + DateUtils.getTimeMillis() + ".docx";LOGGER.info("创建文件路径:" + docName);File targetFile = new File(docName);LOGGER.info("输出新建文件的地址:" + targetFile.getPath());FileOutputStream out = new FileOutputStream(targetFile);xwpfTemplate.write(out);out.flush();out.close();xwpfTemplate.close();//这里可以优化  开发时间紧凑,并为优化excel(targetFile, 0, list, request, response);return docName;}/*** Word中添加表格数据* @param file* @param tableIndex 表格下标* @param list       数据*/public static void excel(File file, int tableIndex, List<List<Map<String, Object>>> list, HttpServletRequest request, HttpServletResponse response) {//读取word源文件LOGGER.info("读取文件  开始加载Excel表格:表格参数=" + list.size());FileInputStream fileInputStream = null;XWPFDocument document = null;List<XWPFTable> tables = null;XWPFTable table = null;XWPFTableRow header = null;List<Map<String, Object>> mapList = null;try {fileInputStream = new FileInputStream(file);document = new XWPFDocument(fileInputStream);//获取所有表格tables = document.getTables();//根据下标获取表格
//            table = tables.get(tableIndex);//获取表头,这里没什么用,只是打印验证下LOGGER.info("正在操作表格的下标:tableIndex=" + tableIndex);
//            LOGGER.info("正在操作表格的标题:table.getText=" + table.getText());//可保留表格的样式(需要重新方法)
//            table.addNewRowBetween(0, 1);LOGGER.info("list条数:" + list.size());
//            if (null != list && list.size() > 0) {//                for (int ni = 0; ni < list.size(); ni++) {//                    table = tables.get(tableIndex);
//                    mapList = list.get(ni);insertTable(tables, list);
//                    header = table.getRow(0);
                    setTableBorderColor(table, "0000FF");
//
//                    LOGGER.info("获取第" + (tableIndex + 1) + "个表格:header=" + header.getTableCells());
//                    LOGGER.info("获取第" + (tableIndex + 1) + "条数据:mapList=" + mapList.size());
                    表格设置参数
//                    if (null != mapList && mapList.size() > 0) {//                        for (int i = 0; i < mapList.size(); i++) {//                            //添加行
                            XWPFTableRow row = table.createRow();
//                            table.addNewRowBetween(0,0);
//                            XWPFTableRow newRow = table.insertNewTableRow(i + 1);
//                            Map<String, Object> zymap = mapList.get(i);
//                            int index = 0;
//                            for (String s : zymap.keySet()) {//                                XWPFTableCell cell = newRow.createCell();//在新增的行上面创建cell
                                newRow.getCell(j).setText(strings1);//给每个cell赋值。
//                                newRow.getCell(index).setText(zymap.get(s).toString());
//                                if (zymap.size() == index) {//                                    index = 0;
//                                } else {//                                    index++;
//                                }
//                            }
//                        }
//                    }
//
                    for (int i = 0; i < tableList.size(); i++) {//遍历要添加的数据的list
                        XWPFTableRow newRow = table.insertNewTableRow(i+1);//为表格添加行
                        String[] strings =  tableList.get(i);//获取list中的字符串数组
                        for (int j = 0; j < strings.length; j++) {//遍历list中的字符串数组
                            String strings1 =  strings[j];
                            newRow.createCell();//在新增的行上面创建cell
                            newRow.getCell(j).setText(strings1);//给每个cell赋值。

                        }
                    }
//                        tableIndex++;
//                }
//            }OutputStream output = new FileOutputStream(file);document.write(output);output.close();document.close();fileInputStream.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}/*** 为表格插入数据,行数不够添加新行* @param tables   需要插入数据的表格* @param list 插入数据集合*/private static void insertTable(List<XWPFTable> tables , List<List<Map<String, Object>>> list) {int tableIndex = 0;XWPFTable table = null;XWPFTableRow header = null;List<Map<String, Object>> mapList = null;if (null != list && list.size() > 0) {for (int ni = 0; ni < list.size(); ni++) {table = tables.get(tableIndex);mapList = list.get(ni);// 添加边框CTTblBorders borders = table.getCTTbl().getTblPr().addNewTblBorders();CTBorder hBorder = borders.addNewInsideH();hBorder.setVal(STBorder.Enum.forString("single"));hBorder.setSz(new BigInteger("1"));hBorder.setColor("000000");CTBorder vBorder = borders.addNewInsideV();vBorder.setVal(STBorder.Enum.forString("single"));vBorder.setSz(new BigInteger("1"));vBorder.setColor("000000");CTBorder lBorder = borders.addNewLeft();lBorder.setVal(STBorder.Enum.forString("single"));lBorder.setSz(new BigInteger("1"));lBorder.setColor("000000");CTBorder rBorder = borders.addNewRight();rBorder.setVal(STBorder.Enum.forString("single"));rBorder.setSz(new BigInteger("1"));rBorder.setColor("000000");CTBorder tBorder = borders.addNewTop();tBorder.setVal(STBorder.Enum.forString("single"));tBorder.setSz(new BigInteger("1"));tBorder.setColor("000000");CTBorder bBorder = borders.addNewBottom();bBorder.setVal(STBorder.Enum.forString("single"));bBorder.setSz(new BigInteger("1"));bBorder.setColor("000000");//创建行,根据需要插入的数据添加新行,不处理表头
//        for (int i = 1; i < tableList.size(); i++) {//            table.createRow();
//        }//        表格设置参数if (null != mapList && mapList.size() > 0) {for (int i = 0; i < mapList.size(); i++) {//添加行XWPFTableRow row = table.createRow();//两种添加行的方式都可以
//                table.addNewRowBetween(0, 0);
//                XWPFTableRow newRow = table.insertNewTableRow(i + 1);Map<String, Object> zymap = mapList.get(i);int index = 0;for (String s : zymap.keySet()) {//                    XWPFTableCell cell = newRow.createCell();//在新增的行上面创建cell
//                                newRow.getCell(j).setText(strings1);//给每个cell赋值。row.getCell(index).setText(zymap.get(s).toString());if (zymap.size() == index) {index = 0;} else {index++;}}}}tableIndex++;}}}/*** 测试方法** @param args* @throws IOException*/public static void main(String[] args) throws IOException {//读取本地图片输入流FileInputStream inStream = new FileInputStream("D://1.jpg");//byte数组用于存放图片字节数据byte[] buff = new byte[inStream.available()];inStream.read(buff);inStream.close();Map<String, Object> data = new HashMap<>();data.put("projectId", "考高巡查");data.put("patrolTypeId", "英语巡查");data.put("inspector", "张三");data.put("date", "2021-04-13");data.put("beginTime", "14:15:03");data.put("content", "英语考试第一次巡查");data.put("result", "一切正常");data.put("endTime", "15:00:00");data.put("note", "无");
//PictureRenderData pictureRenderData = new PictureRenderData(100, 120, "D://1.jpg");data.put("image", pictureRenderData);LOGGER.info("本地图片" + pictureRenderData);String path = WordServiceUtils.class.getClassLoader().getResource("word.docx").getPath();File file = new File(path);LOGGER.info("输出结果获取到的路径:" + file);XWPFTemplate xwpfTemplate = XWPFTemplate.compile(file);LOGGER.info("获取到文件:" + xwpfTemplate);xwpfTemplate.render(data);String docName = "D:\\" + DateUtils.getTimeMillis() + ".docx";File targetFile = new File(docName);LOGGER.info("新建文件的地址:" + targetFile.getPath());FileOutputStream out = new FileOutputStream(targetFile);xwpfTemplate.write(out);//读取word源文件FileInputStream fileInputStream = new FileInputStream(targetFile);XWPFDocument document = new XWPFDocument(fileInputStream);List<XWPFTable> tables = document.getTables();XWPFTable table = tables.get(1);LOGGER.info("获取第一个表格:table.getText=" + table.getText().length());System.out.println("table.getColBandSize()=");
//      XWPFTableRow header = table.getRow(0);
//      LOGGER.info("获取第一个表格:header=" + header.getTableCells());
//        table.addNewRowBetween(0, 3);
//      table.insertNewTableRow(3);
//      table.addRow(table.getRow(5));table.createRow();XWPFTableRow row = table.getRow(1);System.out.println("table.getColBandSize()=" + table.getColBandSize());row.getCell(0).setText("下标为0时");row.getCell(1).setText("下标为1时");row.getCell(2).setText("下标为2时");
//      System.out.println(header.getCell(0).getText());fileInputStream.close();OutputStream output = new FileOutputStream(targetFile);//      out.flush();
//      out.close();
//      xwpfTemplate.close();document.write(output);output.close();}
}

图片统计jfree

package com.ruoyi.common.utils.work;import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
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.PiePlot;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.category.StackedBarRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;public class ChartUtils {private static final String CHART_PATH = "D:/test/";private static final Logger LOGGER = LoggerFactory.getLogger(ChartUtils.class);/*** 生成折线图*/public void makeLineAndShapeChart() {double[][] data = new double[][] { { 672, 766, 223, 540, 126 }, { 325, 521, 210, 340, 106 },{ 332, 256, 523, 240, 526 } };String[] rowKeys = { "苹果", "梨子", "葡萄" };String[] columnKeys = { "北京", "上海", "广州", "成都", "深圳" };CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);createTimeXYChar("折线图", "x轴", "y轴", dataset, "lineAndShap.png");}/*** 生成分组的柱状图*/public void makeBarGroupChart() {double[][] data = new double[][] { { 672, 766, 223, 540, 126 }, { 325, 521, 210, 340, 106 },{ 332, 256, 523, 240, 526 } };String[] rowKeys = { "苹果", "梨子", "葡萄" };String[] columnKeys = { "北京", "上海", "广州", "成都", "深圳" };CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);createBarChart(dataset, "x坐标", "y坐标", "柱状图", "barGroup.png");}/*** 生成柱状图*/public void makeBarChart() {double[][] data = new double[][] { { 672, 766, 223, 540, 126 } };String[] rowKeys = { "苹果" };String[] columnKeys = { "住院药品占比", "上海住院药品占比", "广州", "成都", "深圳" };System.out.println(Arrays.toString(columnKeys));CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);createBarChart(dataset, "x坐标", "y坐标", "柱状图", "bar.png");}/*** 生成堆栈柱状图*/public void makeStackedBarChart() {double[][] data = new double[][] { { 0.21, 0.66, 0.23, 0.40, 0.26 }, { 0.25, 0.21, 0.10, 0.40, 0.16 } };String[] rowKeys = { "苹果", "梨子" };String[] columnKeys = { "北京", "上海", "广州", "成都", "深圳" };CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);createStackedBarChart(dataset, "x坐标", "y坐标", "柱状图", "stsckedBar.png");}/*** 生成饼状图*/public void makePieChart() throws UnsupportedEncodingException {double[] data = { 9, 91 };String[] keys = { "失败率", "成功率" };createValidityComparePimChar(getDataPieSetByUtil(data, keys), "饼状图", "pie2.png", keys);}// 柱状图,折线图 数据集public CategoryDataset getBarData(double[][] data, String[] rowKeys, String[] columnKeys) {return DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data);}// 饼状图 数据集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;}/*** 柱状图** @param dataset    数据集* @param xName      x轴的说明(如种类,时间等)* @param yName      y轴的说明(如速度,时间等)* @param chartTitle 图标题* @param charName   生成图片的名字* @return*/public String createBarChart(CategoryDataset dataset, String xName, String yName, String chartTitle,String charName) {JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 图表标题xName, // 目录轴的显示标签yName, // 数值轴的显示标签dataset, // 数据集PlotOrientation.VERTICAL, // 图表方向:水平、垂直true, // 是否显示图例(对于简单的柱状图必须是false)true, // 是否生成工具false // 是否生成URL链接);
//      Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);Font font = new Font("宋体", Font.BOLD,  12 );TextTitle title = new TextTitle(chartTitle);title.setFont(font);chart.setTitle(title);/** VALUE_TEXT_ANTIALIAS_OFF表示将文字的抗锯齿关闭, 使用的关闭抗锯齿后,字体尽量选择12到14号的宋体字,这样文字最清晰好看*/// chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);chart.setTextAntiAlias(false);chart.setBackgroundPaint(Color.white);// create plotCategoryPlot plot = chart.getCategoryPlot();// 设置横虚线可见plot.setRangeGridlinesVisible(true);// 虚线色彩plot.setRangeGridlinePaint(Color.gray);// 数据轴精度NumberAxis vn = (NumberAxis) plot.getRangeAxis();// vn.setAutoRangeIncludesZero(true);DecimalFormat df = new DecimalFormat("#0.00");vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式// x轴设置CategoryAxis domainAxis = plot.getDomainAxis();domainAxis.setLabelFont(font);// 轴标题domainAxis.setTickLabelFont(font);// 轴数值// Lable(Math.PI/3.0)度倾斜// domainAxis.setCategoryLabelPositions(CategoryLabelPositions// .createUpRotationLabelPositions(Math.PI / 3.0));domainAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 横轴上的 Lable 是否完整显示// 设置距离图片左端距离domainAxis.setLowerMargin(0.1);// 设置距离图片右端距离domainAxis.setUpperMargin(0.1);// 设置 columnKey 是否间隔显示// domainAxis.setSkipCategoryLabelsToFit(true);plot.setDomainAxis(domainAxis);// 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确)plot.setBackgroundPaint(new Color(255, 255, 204));// y轴设置ValueAxis rangeAxis = plot.getRangeAxis();rangeAxis.setLabelFont(font);rangeAxis.setTickLabelFont(font);// 设置最高的一个 Item 与图片顶端的距离rangeAxis.setUpperMargin(0.15);// 设置最低的一个 Item 与图片底端的距离rangeAxis.setLowerMargin(0.15);plot.setRangeAxis(rangeAxis);BarRenderer renderer = new BarRenderer();// 设置柱子宽度renderer.setMaximumBarWidth(0.05);// 设置柱子高度renderer.setMinimumBarLength(0.2);// 设置柱子边框颜色renderer.setBaseOutlinePaint(Color.BLACK);// 设置柱子边框可见renderer.setDrawBarOutline(true);// // 设置柱的颜色renderer.setSeriesPaint(0, new Color(204, 255, 255));renderer.setSeriesPaint(1, new Color(153, 204, 255));renderer.setSeriesPaint(2, new Color(51, 204, 204));// 设置每个地区所包含的平行柱的之间距离renderer.setItemMargin(0.0);// 显示每个柱的数值,并修改该数值的字体属性renderer.setIncludeBaseInRange(true);renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());renderer.setBaseItemLabelsVisible(true);plot.setRenderer(renderer);// 设置柱的透明度plot.setForegroundAlpha(1.0f);FileOutputStream fos_jpg = null;try {isChartPathExist(CHART_PATH);String chartName = CHART_PATH + charName;fos_jpg = new FileOutputStream(chartName);ChartUtilities.writeChartAsPNG(fos_jpg, chart, 1000, 950, true, 10);LOGGER.info("返回参数=" + CHART_PATH+charName);return CHART_PATH+charName;} catch (Exception e) {e.printStackTrace();return null;} finally {try {fos_jpg.close();} catch (Exception e) {e.printStackTrace();}}}/*** 横向图** @param dataset    数据集* @param xName      x轴的说明(如种类,时间等)* @param yName      y轴的说明(如速度,时间等)* @param chartTitle 图标题* @param charName   生成图片的名字* @return*/public String createHorizontalBarChart(CategoryDataset dataset, String xName, String yName, String chartTitle,String charName) {JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 图表标题xName, // 目录轴的显示标签yName, // 数值轴的显示标签dataset, // 数据集PlotOrientation.VERTICAL, // 图表方向:水平、垂直true, // 是否显示图例(对于简单的柱状图必须是false)false, // 是否生成工具false // 是否生成URL链接);CategoryPlot plot = chart.getCategoryPlot();// 数据轴精度NumberAxis vn = (NumberAxis) plot.getRangeAxis();// 设置刻度必须从0开始// vn.setAutoRangeIncludesZero(true);DecimalFormat df = new DecimalFormat("#0.00");vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式CategoryAxis domainAxis = plot.getDomainAxis();domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 横轴上的// LableFont labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);domainAxis.setLabelFont(labelFont);// 轴标题domainAxis.setTickLabelFont(labelFont);// 轴数值domainAxis.setMaximumCategoryLabelWidthRatio(0.8f);// 横轴上的 Lable 是否完整显示// domainAxis.setVerticalCategoryLabels(false);plot.setDomainAxis(domainAxis);ValueAxis rangeAxis = plot.getRangeAxis();// 设置最高的一个 Item 与图片顶端的距离rangeAxis.setUpperMargin(0.15);// 设置最低的一个 Item 与图片底端的距离rangeAxis.setLowerMargin(0.15);plot.setRangeAxis(rangeAxis);BarRenderer renderer = new BarRenderer();// 设置柱子宽度renderer.setMaximumBarWidth(0.03);// 设置柱子高度renderer.setMinimumBarLength(30);renderer.setBaseOutlinePaint(Color.BLACK);// 设置柱的颜色renderer.setSeriesPaint(0, Color.GREEN);renderer.setSeriesPaint(1, new Color(0, 0, 255));// 设置每个地区所包含的平行柱的之间距离renderer.setItemMargin(0.5);// 显示每个柱的数值,并修改该数值的字体属性renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());// 设置柱的数值可见renderer.setBaseItemLabelsVisible(true);plot.setRenderer(renderer);// 设置柱的透明度plot.setForegroundAlpha(0.6f);FileOutputStream fos_jpg = null;try {isChartPathExist(CHART_PATH);String chartName = CHART_PATH + charName;fos_jpg = new FileOutputStream(chartName);ChartUtilities.writeChartAsPNG(fos_jpg, chart, 1000, 950, true, 10);return chartName;} catch (Exception e) {e.printStackTrace();return null;} finally {try {fos_jpg.close();} catch (Exception e) {e.printStackTrace();}}}/*** 饼状图** @param dataset    数据集* @param chartTitle 图标题* @param charName   生成图的名字* @param pieKeys    分饼的名字集* @return*/public String createValidityComparePimChar(PieDataset dataset, String chartTitle, String charName,String[] pieKeys) throws UnsupportedEncodingException {byte[] utfByte = chartTitle.getBytes(StandardCharsets.UTF_8);String utfstr = new String(utfByte, "UTF-8");JFreeChart chart = ChartFactory.createPieChart(chartTitle, // chart// titledataset, // datafalse, // include legendtrue, false);// 使下说明标签字体清晰,去锯齿类似于chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);chart.setTextAntiAlias(false);// 图片背景色chart.setBackgroundPaint(Color.white);// 设置图标题的字体重新设置titleFont font = new Font("宋体", Font.BOLD,  12 );TextTitle title = new TextTitle(chartTitle);title.setFont(font);chart.setTitle(title);PiePlot plot = (PiePlot) chart.getPlot();// 图片中显示百分比:默认方式// 指定饼图轮廓线的颜色// plot.setBaseSectionOutlinePaint(Color.BLACK);// plot.setBaseSectionPaint(Color.BLACK);System.out.println(plot.getLabelFont());// 设置无数据时的信息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("宋体", Font.BOLD, 12));System.out.println(plot.getLabelFont());//     CategoryPlot goryplot = chart.getCategoryPlot();    //获得图表区域对象
//      CategoryAxis domainAxis = plot.get
//      domainAxis.setVisible(true);
//      goryplot.setDomainAxis(domainAxis);
//      ValueAxis rAxis = goryplot.getRangeAxis();
//      rAxis.setTickLabelFont(new Font("宋体",Font.PLAIN,15));// 指定图片的透明度(0.0-1.0)
//      plot.setForegroundAlpha(0.65f);plot.setForegroundAlpha(1.0f);// 指定显示的饼图上圆形(false)还椭圆形(true)plot.setCircular(true, true);// 设置第一个 饼块section 的开始位置,默认是12点钟方向plot.setStartAngle(90);// // 设置分饼颜色plot.setSectionPaint(pieKeys[0], new Color(244, 194, 144));plot.setSectionPaint(pieKeys[1], new Color(144, 233, 144));FileOutputStream fos_jpg = null;try {// 文件夹不存在则创建isChartPathExist(CHART_PATH);String chartName = CHART_PATH + charName;fos_jpg = new FileOutputStream(chartName);// 高宽的设置影响椭圆饼图的形状ChartUtilities.writeChartAsPNG(fos_jpg, chart, 1000, 950);return chartName;} catch (Exception e) {e.printStackTrace();return null;} finally {try {fos_jpg.close();System.out.println("create pie-chart close file system.");} catch (Exception e) {e.printStackTrace();}}}/*** 判断文件夹是否存在,如果不存在则新建** @param chartPath*/private void isChartPathExist(String chartPath) {File file = new File(chartPath);if (!file.exists()) {file.mkdirs();// log.info("CHART_PATH="+CHART_PATH+"create.");}}/*** 折线图** @param chartTitle* @param x* @param y* @param xyDataset* @param charName* @return*/public String createTimeXYChar(String chartTitle, String x, String y, CategoryDataset xyDataset, String charName) {JFreeChart chart = ChartFactory.createLineChart(chartTitle, x, y, xyDataset, PlotOrientation.VERTICAL, true,true, false);chart.setTextAntiAlias(true);chart.setBackgroundPaint(Color.WHITE);// 设置图标题的字体重新设置titleFont font = new Font("隶书", Font.BOLD, 25);TextTitle title = new TextTitle(chartTitle);title.setFont(font);chart.setTitle(title);// 设置面板字体Font labelFont = new Font("隶书", Font.BOLD, 12);chart.setBackgroundPaint(Color.WHITE);CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
//      categorical.setNoDataMessagePaint(Color.red);// x轴 // 分类轴网格是否可见categoryplot.setDomainGridlinesVisible(true);// y轴 //数据轴网格是否可见categoryplot.setRangeGridlinesVisible(true);categoryplot.setRangeGridlinePaint(Color.WHITE);// 虚线色彩categoryplot.setDomainGridlinePaint(Color.WHITE);// 虚线色彩categoryplot.setBackgroundPaint(Color.lightGray);categoryplot.setNoDataMessageFont(new Font("隶书", Font.BOLD, 12));// 设置轴和面板之间的距离// categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));CategoryAxis domainAxis = categoryplot.getDomainAxis();domainAxis.setLabelFont(labelFont);// 轴标题domainAxis.setTickLabelFont(labelFont);// 轴数值domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 横轴上的// Lable// 45度倾斜// 设置距离图片左端距离domainAxis.setLowerMargin(0.0);// 设置距离图片右端距离domainAxis.setUpperMargin(0.0);NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());numberaxis.setAutoRangeIncludesZero(true);// 获得renderer 注意这里是下嗍造型到lineandshaperenderer!!LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer();lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见// 显示折点数据// lineandshaperenderer.setBaseItemLabelGenerator(new// StandardCategoryItemLabelGenerator());// lineandshaperenderer.setBaseItemLabelsVisible(true);FileOutputStream fos_jpg = null;try {isChartPathExist(CHART_PATH);String chartName = CHART_PATH + charName;fos_jpg = new FileOutputStream(chartName);// 将报表保存为png文件ChartUtilities.writeChartAsPNG(fos_jpg, chart, 1000, 950);return chartName;} catch (Exception e) {e.printStackTrace();return null;} finally {try {fos_jpg.close();System.out.println("create time-createTimeXYChar.");} catch (Exception e) {e.printStackTrace();}}}/*** 堆栈柱状图** @param dataset* @param xName* @param yName* @param chartTitle* @param charName* @return*/public String createStackedBarChart(CategoryDataset dataset, String xName, String yName, String chartTitle,String charName) {// 1:得到 CategoryDataset// 2:JFreeChart对象JFreeChart chart = ChartFactory.createStackedBarChart(chartTitle, // 图表标题xName, // 目录轴的显示标签yName, // 数值轴的显示标签dataset, // 数据集PlotOrientation.VERTICAL, // 图表方向:水平、垂直true, // 是否显示图例(对于简单的柱状图必须是false)false, // 是否生成工具false // 是否生成URL链接);// 图例字体清晰chart.setTextAntiAlias(false);chart.setBackgroundPaint(Color.WHITE);// 2 .2 主标题对象 主标题对象是 TextTitle 类型chart.setTitle(new TextTitle(chartTitle, new Font("隶书", Font.BOLD, 25)));// 2 .2.1:设置中文// x,y轴坐标字体Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);// 2 .3 Plot 对象 Plot 对象是图形的绘制结构对象CategoryPlot plot = chart.getCategoryPlot();// 设置横虚线可见plot.setRangeGridlinesVisible(true);// 虚线色彩plot.setRangeGridlinePaint(Color.gray);// 数据轴精度NumberAxis vn = (NumberAxis) plot.getRangeAxis();// 设置最大值是1vn.setUpperBound(1);// 设置数据轴坐标从0开始// vn.setAutoRangeIncludesZero(true);// 数据显示格式是百分比DecimalFormat df = new DecimalFormat("0.00%");vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式// DomainAxis (区域轴,相当于 x 轴), RangeAxis (范围轴,相当于 y 轴)CategoryAxis domainAxis = plot.getDomainAxis();domainAxis.setLabelFont(labelFont);// 轴标题domainAxis.setTickLabelFont(labelFont);// 轴数值// x轴坐标太长,建议设置倾斜,如下两种方式选其一,两种效果相同// 倾斜(1)横轴上的 Lable 45度倾斜// domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);// 倾斜(2)Lable(Math.PI 3.0)度倾斜// domainAxis.setCategoryLabelPositions(CategoryLabelPositions// .createUpRotationLabelPositions(Math.PI / 3.0));domainAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 横轴上的 Lable 是否完整显示plot.setDomainAxis(domainAxis);// y轴设置ValueAxis rangeAxis = plot.getRangeAxis();rangeAxis.setLabelFont(labelFont);rangeAxis.setTickLabelFont(labelFont);// 设置最高的一个 Item 与图片顶端的距离rangeAxis.setUpperMargin(0.15);// 设置最低的一个 Item 与图片底端的距离rangeAxis.setLowerMargin(0.15);plot.setRangeAxis(rangeAxis);// Renderer 对象是图形的绘制单元StackedBarRenderer renderer = new StackedBarRenderer();// 设置柱子宽度renderer.setMaximumBarWidth(0.05);// 设置柱子高度renderer.setMinimumBarLength(0.1);// 设置柱的边框颜色renderer.setBaseOutlinePaint(Color.BLACK);// 设置柱的边框可见renderer.setDrawBarOutline(true);// // 设置柱的颜色(可设定也可默认)renderer.setSeriesPaint(0, new Color(204, 255, 204));renderer.setSeriesPaint(1, new Color(255, 204, 153));// 设置每个地区所包含的平行柱的之间距离renderer.setItemMargin(0.4);plot.setRenderer(renderer);// 设置柱的透明度(如果是3D的必须设置才能达到立体效果,如果是2D的设置则使颜色变淡)// plot.setForegroundAlpha(0.65f);FileOutputStream fos_jpg = null;try {isChartPathExist(CHART_PATH);String chartName = CHART_PATH + charName;fos_jpg = new FileOutputStream(chartName);ChartUtilities.writeChartAsPNG(fos_jpg, chart, 1000, 950, true, 10);return chartName;} catch (Exception e) {e.printStackTrace();return null;} finally {try {fos_jpg.close();} catch (Exception e) {e.printStackTrace();}}}
}

文档模板

package com.ruoyi.common.utils.work;import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.zmfblsj.total.domain.BlsjTotal;
import com.ruoyi.project.zmfblsj.total.domain.QueryTotal;import org.apache.commons.collections.map.LinkedMap;import java.util.Arrays;
import java.util.Map;/*** Word模板类*/
public class abc {private static String title = "%s医疗保健安全质量分析报告";private static String text1 = "为发现医疗过程中存在的安全隐患、防范医疗事故、提高医疗质量、保障患者安全、" +"促进核心制度的落实,我院特制定下发了《洛阳市妇幼保健院医疗安全(不良)事件上报制度》,各科室严格执行、" +"按规定及时主动上报不良事件。截止%s月至%s月,全院共发生医疗安全(不良)事件%s例," +"未发生重大不良事件。现将各科室报告医疗安全不良事件进行分析,以达到消除安全隐患,防范医疗事故及纠纷,不断提高医疗质量的目的";private static String text2 = "1.%s月至%s月上报例数(图一):";private static String text3 = "2.%s月至%s月不良事件分级(图二):";private static String text4 = "3.%s月至%s月上报不良事件科室分布(图三):";private static String text5 = "4.不良事件的分类(图三):";private static String text6 = "5.各类不良事件的发生趋势(图四):";//各类事件汇总private static String text7 = "截止到%s年%s月共收到不良事件%s件,其中第一季度%s件。";private static String text8 = "第一季度的%s件不良事件中,均由%s上报,其中%s事件,有%s例";private static String text9 = "%s到%s,全院共上报护理安全(不良)事件%s例,具体情况汇总如下:";private static String text10 = "4.不良事件的分类(图三):";private static String text11 = "截止%s,我院发生Ⅰ级不良事件上报%s例,Ⅱ级不良事件上报%s例,Ⅲ级不良事件上报%s例,Ⅳ级不良事件上报%s例;已上报的%s例护理不良事件,";private static String text12 = "%s";//防控感染private static String text13 = "%s共上报职业暴露不良事件%s例,暴露人员中上报人员占%s例,";private static String text14 = "%s职业暴露不良事件高达%s例,经过采取知识培训、穿脱防护用品技能大赛、设计利器盒等一系列措施";//药品事件private static String text15 = "%s药事不良事件共%s例,其中药品不良反应%s例";//医疗器械不良事件private static String text16 = "%s,全院共上报医疗器械不良事件%s例,上报人员占%s例,具体情况汇总如下";private static String text17 = "截止%s,我院医疗器械发生Ⅰ、Ⅱ级不良事件,Ⅲ级不良事件上报23例,Ⅳ级不良事件上报5例;已上报的28例护理不良事件";//    总结private static String text18 = "从%s";private static String text19 = "%s共上报不良事件%s例";private static String text20 = "%s零上报的科室有:%s";public static Map setTemp(QueryTotal query){BlsjTotal blsj = new BlsjTotal();StringBuffer moth = new StringBuffer();StringBuffer quarter = new StringBuffer();Map<String,Object> data =new LinkedMap();data.put("title",String.format(title, query.getBeginTime()+"至"+query.getEndTime()));data.put("text1", String.format(text1, query.getBeginTime(), query.getEndTime(), query.getTotalCount()));data.put("text2", String.format(text2,query.getBeginTime(), query.getEndTime()));data.put("text3", String.format(text3,query.getBeginTime(), query.getEndTime()));data.put("text4", String.format(text4,query.getBeginTime(), query.getEndTime()));data.put("text5", String.format(text5));data.put("text6", String.format(text6));data.put("text7", String.format(text7, DateUtils.getYear(), moth, query.getTotalCount(), query.getFirst()));//        data.put("text8", String.format(text8, query.getTotalCount(), "麻醉科上报", "一级事件", 1));data.put("text9", String.format(text9,query.getBeginTime(), query.getEndTime(), query.getTotalCount()));data.put("text10", String.format(text10));data.put("text11", String.format(text11, query.getEndTime(), query.getOneNum(), query.getTwoNum(), query.getThreeNum(),query.getFirst(),query.getTotalCount()));data.put("text12", String.format(text12, query.getStrDept()));data.put("text13", String.format(text13, query.getBeginTime()+"至"+query.getEndTime(), query.getYgcount(), query.getYgrate()));data.put("text14", String.format(text14, query.getBeginTime()+"至"+query.getEndTime(), query.getYgcount()));data.put("text15", String.format(text15, query.getBeginTime()+"至"+query.getEndTime(), query.getFycount(), query.getYpcount()));data.put("text16", String.format(text16, query.getBeginTime()+"至"+query.getEndTime(), query.getQxCount(), query.getQxRate()));data.put("text18", String.format(text18, query.getBeginTime()+"至"+query.getEndTime()));data.put("text19", String.format(text19, query.getBeginTime()+"至"+query.getEndTime(), query.getTotalCount()));data.put("text20", String.format(text20, query.getStrDept(), Arrays.toString(query.getNotReportDept())));return data;}}

文档下载

package com.ruoyi.project.zmfblsj.total.controller;import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.work.ChartUtils;
import com.ruoyi.common.utils.work.ToArrayUtils;
import com.ruoyi.common.utils.work.WordServiceUtils;
import com.ruoyi.common.utils.work.abc;
import com.ruoyi.project.zmfblsj.total.domain.BlsjTotal;
import com.ruoyi.project.zmfblsj.total.domain.QueryTotal;
import com.ruoyi.project.zmfblsj.total.service.IBlsjTotalService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.general.DefaultPieDataset;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;/*** 下载Word文档* scl*/
@RestController
@RequestMapping("api/test/")
public class WordTestController {private static final Logger LOGGER = LoggerFactory.getLogger(WordTestController.class);private static String begin = null;private static String end = null;@Autowiredprivate IBlsjTotalService totalService;@RequiresPermissions("zmfblsj:total:loadWord")@RequestMapping(value = "exportData", method = RequestMethod.GET)public void exportData(HttpServletRequest request, HttpServletResponse response)throws Exception {LOGGER.info("*************进入下载Word文档***************");//接收前端传递的参数String beginTime = request.getParameter("beginTime");String endTime = request.getParameter("endTime");BlsjTotal blsjTotal = new BlsjTotal();/*因会加载两次,所以做了数据处理*/if (null == beginTime || beginTime.equals("")){blsjTotal.setBeingTime(begin);} else {begin = beginTime;blsjTotal.setBeingTime(beginTime);}if (null == endTime || endTime.equals("")){blsjTotal.setEndTime(end);} else {end = endTime;blsjTotal.setEndTime(endTime);}
//        blsjTotal.setBeingTime(beginTime);
//        blsjTotal.setEndTime(endTime);LOGGER.info("下载分析报告方法入参:选择时间="+blsjTotal.getBeingTime()+",结束时间="+blsjTotal.getEndTime());LOGGER.info("*************开始处理文档的数据,选择文档的开始时间beginTime=" + beginTime + ",endTime=" + endTime + "**********");//图片集合List<String> pictureTag = new ArrayList<>();LOGGER.info("*************开始加载Word模板的数据已经模板文字***************");Map<String, Object> data = new HashMap<>();// 需要填充的数据,key为模板中的变量data = abc.setTemp(getBlsjCountByTime(blsjTotal));LOGGER.info("模板数据:"+data);
//        String[] files = dto.getFiles().split("-");//统计数据  生成图片BlsjTotal ylincome = new BlsjTotal();LOGGER.info("*************开始加载统计图片的数据***************");//获取图片信息//根据月份统计String imgUrl = docLevelImg(ylincome);pictureTag.add(imgUrl);String levelImg = levelImg(ylincome);pictureTag.add(levelImg);String deptPieImg = deptPieImg(ylincome);pictureTag.add(deptPieImg);String catepieImg = catepieImg(ylincome);pictureTag.add(catepieImg);// 护理级别统计图BlsjTotal level = new BlsjTotal();level.setBeingTime(beginTime);level.setEndTime(endTime);level.setTitle("护理");String levelPieImg = levelPieImg(ylincome);pictureTag.add(levelPieImg);LOGGER.info("*************加载文档中表格的数据***************");//数据表格集合List<List<Map<String, Object>>> tableList = new ArrayList<>();//表格数据  需要重数据库中获取/*事件级别列表*/List<Map<String, Object>> countLevel = totalService.queryCountLevel(ylincome);tableList.add(countLevel);/*护理Excel*/BlsjTotal blsj = new BlsjTotal();blsj.setBeingTime(ylincome.getBeingTime());blsj.setEndTime(ylincome.getEndTime());blsj.setTitle("护理");List<Map<String, Object>> hlDeptList = totalService.hlDeptList(blsj);tableList.add(hlDeptList);/*护理上报最多的科室*/List<Map<String, Object>> hlSort = totalService.deptFixedSort(blsj);tableList.add(hlSort);/*器械Excel*/List<Map<String, Object>> sortqx = totalService.deptSortqx(ylincome);tableList.add(sortqx);
//      /*科室事例上报*/
//      List<Map<String, Object>> titleBysort = totalService.deptCountTitleBysort(ylincome);
//      tableList.add(titleBysort);
//      /*上报最多的科室*/
//      List<Map<String, Object>> fixedSort = totalService.deptFixedSort(ylincome);
//      tableList.add(fixedSort);LOGGER.info("*******表格数据:countLevel=" + countLevel + ",titleBysort=" + null + ",fixedSort=" + null+ ",sortqx=" + sortqx + ",hlDeptList=" + hlDeptList);LOGGER.info("*******表格数据:countLevel=" + countLevel.size() + ",titleBysort=" + null + ",fixedSort=" + null+ ",sortqx=" + sortqx.size() + ",hlDeptList=" + hlDeptList.size());LOGGER.info("*************加载Word模板***************");
//      String templatePath = "/yzcx/src/main/resources/word.docx";//增加多张图片需要在模板类页面  添加多个valuei   模板放在resources/ehcache,最后生成的文件为.docx//处理图片信息  现更改为模板无限增加图片,这里暂不做处理//图片的处理 我放在了WordServiceUtils,这里暂不处理,如果改变图片添加的灵动性,可以考虑在这里做图片的处理
//      String[] files = new String[] { "1" };
//      for (int i = 0; i < num; i++) {//          String photoPath = barPuth;
//          File fl = new File(barPuth);
//          // 这个类完全是为了获取图片长宽
//          data.put("img1", photoPath);
//          // 标识出其中的图片变量,需要特殊处理
            pictureTag.add("image");
//          LOGGER.info("入参data{}="+data);
//      }
//       多种图片 :对应三种数量图片的模                                                                                                  板路径
//      switch (num) {//      case 1:
//          templatePath = "/yzcx/src/main/resources/word.docx";
//          break;
//      case 2:
//          templatePath = "/yzcx/src/main/resources/word.docx";
//          break;
//      case 3:
//          templatePath = "/yzcx/src/main/resources/word.docx";
//          break;
//      }LOGGER.info("*************开始封装数据***************");String patrol = WordServiceUtils.downWord(data, null, pictureTag, "patrol", tableList, request, response);downFile(request, response, null, new File(patrol));LOGGER.info("**********文件流写出***********");}/*** 基础字节数组输出*/public static void downFile(HttpServletRequest request, HttpServletResponse response, String filename, File file) throws IOException {LOGGER.info("文件下载地址:file"+file.getPath());//  文件存在才下载OutputStream out = null;FileInputStream in = null;String docxName= file.getName();try {// 1.读取要下载的内容in = new FileInputStream(file);// 2. 告诉浏览器下载的方式以及一些设置// 解决文件名乱码问题,获取浏览器类型,转换对应文件名编码格式,IE要求文件名必须是utf-8, firefo要求是iso-8859-1编码String agent = request.getHeader("user-agent");if (agent.contains("FireFox")) {docxName = new String(docxName.getBytes("UTF-8"), "iso-8859-1");} else {docxName = URLEncoder.encode(docxName, "UTF-8");}// 设置下载文件的mineType,告诉浏览器下载文件类型String mineType = request.getServletContext().getMimeType(docxName);response.setContentType(mineType);// 设置一个响应头,无论是否被浏览器解析,都下载response.setHeader("Content-disposition", "attachment; filename=" + docxName);// 将要下载的文件内容通过输出流写到浏览器out = response.getOutputStream();int len = 0;byte[] buffer = new byte[1024];while ((len = in.read(buffer)) > 0) {out.write(buffer, 0, len);}} catch (IOException e) {e.printStackTrace();} finally {if (out != null) {out.close();}if (in != null) {in.close();}}}/* 设置文档的参数 */public QueryTotal getBlsjCountByTime(BlsjTotal blsjTotal) {QueryTotal query = new QueryTotal();query.setBeginTime(blsjTotal.getBeingTime());query.setEndTime(blsjTotal.getEndTime());try {List<Map<String, Object>> countByTime = totalService.blsjCountByTime(blsjTotal);if (null != countByTime && countByTime.size() > 0) {for (Map<String, Object> str : countByTime) {query.setTotalCount(str.get("TOTALCOUNT").toString());query.setFirst(str.get("ONECOUNT").toString());}}} catch (Exception e) {e.printStackTrace();LOGGER.info("全年或者时间段获取事例有误");}try {List<Map<String, Object>> countLevel = totalService.queryCountLevel(blsjTotal);LOGGER.info("事件级别出参:" + countLevel);if (null != countLevel && countLevel.size() > 0) {for (Map<String, Object> str : countLevel) {query.setOneNum(str.get("I").toString());query.setTwoNum(str.get("II").toString());query.setThreeNum(str.get("III").toString());query.setFourNum(str.get("IV").toString());}}} catch (Exception e) {e.printStackTrace();LOGGER.info("各个事件等级获取事例有误");}try {/*test12 */List<Map<String, Object>> countDept = totalService.queryCountDept(blsjTotal);LOGGER.info("test12出参:" + countDept);int len = 0;int i = 1;StringBuilder values = new StringBuilder();if (null != countDept && countDept.size() > 0) {for (Map<String, Object> map : countDept) {len = map.size();values.append(map.get("DEPT_NAME")).append(map.get("COUNTS")).append("例,");i++;}}query.setStrDept(values.toString());LOGGER.info("拼接之后的字符串str=" + query.getStrDept());
//          str[i] = values.toString();
//          query.setArrMap(str);} catch (Exception e) {e.printStackTrace();}/*分类占比*/try {BlsjTotal yg = new BlsjTotal();yg.setTitle("职业暴露");yg.setBeingTime(blsjTotal.getBeingTime());yg.setEndTime(blsjTotal.getEndTime());LOGGER.info(yg.getTitle() + "," + yg.getBeingTime() + "," + yg.getEndTime());List<Map<String, Object>> roundCount = totalService.ygRoundCount(yg);LOGGER.info("职业暴露出参:" + roundCount);if (null != roundCount && roundCount.size() > 0) {for (Map<String, Object> map : roundCount) {query.setYgcount(map.get("ZYCOUNT").toString());query.setYgrate(map.get("RATE").toString());}}} catch (Exception e) {e.printStackTrace();}/*器械*/try {BlsjTotal yg = new BlsjTotal();yg.setTitle("医疗器械");yg.setBeingTime(blsjTotal.getBeingTime());yg.setEndTime(blsjTotal.getEndTime());List<Map<String, Object>> roundCount = totalService.ygRoundCount(yg);LOGGER.info("器械统计出参:" + roundCount);if (null != roundCount && roundCount.size() > 0) {for (Map<String, Object> map : roundCount) {query.setQxCount(map.get("ZYCOUNT").toString());query.setQxRate(map.get("RATE").toString());}}} catch (Exception e) {e.printStackTrace();}/*药品统计*/try {List<Map<String, Object>> ypCount = totalService.ypCountByTime(blsjTotal);LOGGER.info("药品统计出参:" + ypCount);if (null != ypCount && ypCount.size() > 0) {for (Map<String, Object> map : ypCount) {query.setYpcount(map.get("YPCOUNT").toString());query.setFycount(map.get("FYCOUNT").toString());}}} catch (Exception e) {e.printStackTrace();}/*0上报科室*/try {List<Map<String, Object>> noIsReportDept = totalService.noIsReportDept(blsjTotal);LOGGER.info("零上报科室出参:" + noIsReportDept);String[] arrDept = new String[noIsReportDept.size()];if (null != noIsReportDept && noIsReportDept.size() > 0) {for (int a = 0; a < noIsReportDept.size(); a++) {Map<String, Object> map = noIsReportDept.get(a);arrDept[a] = map.get("DEPT_NAME").toString();}}query.setNotReportDept(arrDept);LOGGER.info("零上报科室:" + Arrays.toString(arrDept));} catch (Exception e) {e.printStackTrace();}LOGGER.info("模板添加数据:" + query);return query;}/*** 根据月份统计** @param ylincome* @return* @throws Exception*/public String docLevelImg(BlsjTotal ylincome) throws Exception {LOGGER.info("*************生成月份统计图,以及处理图片***************");double[][] dataset = null;List<String> list = new ArrayList<>();String[] rowKeys = {"月份统计"};List<Map<String, Object>> docLevelCount = totalService.queryByMount(ylincome);LOGGER.info("根据月份统计结果出参sql=" + docLevelCount);if (null != docLevelCount && docLevelCount.size() > 0) {dataset = ToArrayUtils.ListToArray(docLevelCount, docLevelCount.size(), null);for (int i = 0; i < docLevelCount.size(); i++) {Map<String, Object> map = docLevelCount.get(i);String keys = (String) map.get("DAYS");list.add(keys);}}String[] array = list.toArray(new String[0]);System.out.println(Arrays.toString(array));ChartUtils chartUtils = new ChartUtils();CategoryDataset categoryDataset = DatasetUtilities.createCategoryDataset(array, rowKeys, dataset);String barPuth = chartUtils.createBarChart(categoryDataset, "x坐标", "y坐标", "不良事件上报例数", DateUtils.getTimeMillis() + ".png");return barPuth;}/*** 根据事件级别统计** @param ylincome* @return* @throws Exception*/public String levelImg(BlsjTotal ylincome) throws Exception {LOGGER.info("*************根据事件级别统计生成图片,以及处理图片***************");CategoryDataset dataset = null;String[] rowKeys = {"月份统计"};List<Map<String, Object>> list = totalService.queryBylevel(ylincome);LOGGER.info("事件级别统计图查询结果出参sql=" + list);if (null != list) {for (int i = 0; i < list.size(); i++) {Map<String, Object> map = list.get(i);dataset = ToArrayUtils.mapToArray(map, list.size(), rowKeys);}}LOGGER.info("*************生成月份统计图,以及处理图片***************");ChartUtils chartUtils = new ChartUtils();String barPuth = chartUtils.createBarChart(dataset, "x坐标", "y坐标", "事件级别统计", DateUtils.getTimeMillis() + ".png");
//      pictureTag.add(barPuth);LOGGER.info("最后统计图片的地址:" + barPuth);return barPuth;}/*** 科室发生事件统计生成图片** @param ylincome* @return* @throws Exception*/public String deptPieImg(BlsjTotal ylincome) throws Exception {LOGGER.info("*************科室发生事件统计生成图片,以及处理图片***************");List<Map<String, Object>> list = totalService.queryCountDept(ylincome);List<String> keys = new ArrayList<>();DefaultPieDataset dataset = new DefaultPieDataset();if (null != list && list.size() > 0) {for (int i = 0; i < list.size(); i++) {Map<String, Object> map = list.get(i);String dept_name = (String) map.get("DEPT_NAME");BigDecimal counts = (BigDecimal) map.get("COUNTS");keys.add(dept_name);dataset.setValue(dept_name, counts);}}ChartUtils chartUtils = new ChartUtils();String[] array = keys.toArray(new String[0]);String imgPath = chartUtils.createValidityComparePimChar(dataset, "科室发生事件统计", DateUtils.getTimeMillis() + ".png", array);return imgPath;}/*** 事件归类** @param ylincome* @return* @throws UnsupportedEncodingException*/public String catepieImg(BlsjTotal ylincome) throws UnsupportedEncodingException {LOGGER.info("*************事件归类统计,以及处理图片***************");List<Map<String, Object>> qryResList = totalService.selectBlsjByType(ylincome.getBeingTime(), ylincome.getEndTime());List<String> keys = new ArrayList<>();DefaultPieDataset dataset = new DefaultPieDataset();if (null != qryResList && qryResList.size() > 0) {for (int i = 0; i < qryResList.size(); i++) {Map<String, Object> map = qryResList.get(i);String dept_name = (String) map.get("TYPE_NAME");BigDecimal counts = (BigDecimal) map.get("NUM");keys.add(dept_name);dataset.setValue(dept_name, counts);}}ChartUtils chartUtils = new ChartUtils();String[] array = keys.toArray(new String[0]);String imgPath = chartUtils.createValidityComparePimChar(dataset, "事件分类", DateUtils.getTimeMillis() + ".png", array);return imgPath;}/*** 护理级别事件统计** @param ylincome* @return*/public String levelPieImg(BlsjTotal ylincome) {CategoryDataset dataset = null;String[] rowKeys = {"级别统计"};List<Map<String, Object>> qryResList = totalService.queryCountLevel(ylincome);if (null != qryResList && qryResList.size() > 0) {int a = 0;for (int i = 0; i < qryResList.size(); i++) {Map<String, Object> map = qryResList.get(i);dataset = ToArrayUtils.mapToArray(map, qryResList.size(), rowKeys);}}LOGGER.info("*************护理级别事件统计,以及处理图片***************");ChartUtils chartUtils = new ChartUtils();/*(rowKeys, columnKeys, data);*/String barPuth = chartUtils.createBarChart(dataset, "x坐标", "y坐标", "护理事件级别统计", DateUtils.getTimeMillis() + ".png");return barPuth;}
}
package com.ruoyi.common.utils.work;import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.springframework.util.CollectionUtils;import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;/*** map list<map>转换数组工具*/
public class ToArrayUtils {/***@Description: list列表转换成二维数组*@param: @param list*@param: @param KeyLenght每行的列数,按最长的计算*@param: @return*@return Object[][]*/public static double[][] ListToArray(List<Map<String, Object>> list, int KeyLenght, String values) {if (CollectionUtils.isEmpty(list)) {return new double[0][];}int size = list.size();
//        Object[][] array = new Object[size][KeyLenght];int a = 0;for (int i = 0; i < size; i++) {//循环遍历所有行
//            array[i] = list.get(i).values().toArray();//每行的列数a++;}//二维数组初始化数据double[][] result=new double[a][];for(int i=0;i<list.size();i++) {Map<String, Object> map=list.get(i);//循环设置数组元素result[i]= new double[]{new Double(String.valueOf(map.get("COUNTS")))};}System.out.println(Arrays.toString(result));return result;}/*** 单条数据可用* @param map* @param KeyLenght* @return*/public static CategoryDataset mapToArray(Map<String, Object> map, int KeyLenght, String rowKeys[]) {//        if (CollectionUtils.isEmpty(map)) {0.
//            return new double[0][];
//        }int size = map.size();double[][] array = new double[KeyLenght][size];Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();String keyName = "";String valueName = "";int i = 0;String columnKeys[] = new String[size];while (iterator.hasNext()){Map.Entry<String, Object> entry = iterator.next();keyName = entry.getKey().toString();columnKeys[i] = keyName;valueName = entry.getValue().toString();array[KeyLenght-1][i] = Double.parseDouble(valueName.toString());//每行的列数i++;}CategoryDataset dataset = DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, array);return dataset;}
}

Word文档下载(图片,数据表格)相关推荐

  1. Python 操作Word文档插入图片和表格实例演示

    Python 操作Word文档插入图片和表格实例演示 效果图 实现过程 ① python-docx 库安装 ② word 文档插入图片演示 ③ word 文档插入表格演示 [ 文章推荐 ] Pytho ...

  2. python 给word添加背景图片_Python如何使用word文档插入图片和表格

    Python如何使用word文档插入图片和表格 发布时间:2020-10-26 13:49:29 来源:亿速云 阅读:101 作者:挣扎的蓝藻 这篇文章运用简单易懂的例子给大家介绍Python如何使用 ...

  3. python打开word并插入图片_Python操作word文档插入图片和表格的实例演示

    前言 图片是Word的一种特殊内容,这篇文章主要介绍了关于Python操作word文档,向里面插入图片和表格的相关内容,下面话不多说了,来一起看看详细的代码 实例代码: # -*- coding: U ...

  4. 【.NET】用Aspose.Words for .NET动态生成word文档中的数据表格

    1.概述 最近项目中有一个这样的需求:导出word 文档,要求这个文档的格式不是固定的,用户可以随便的调整,导出内容中的数据表格列是动态的,例如要求导出姓名和性别,你就要导出这两列的数据,而且这个文档 ...

  5. php怎么在表格里插图片,Python操作word文档插入图片和表格的实例演示

    今天带来Python操作word文档插入图片和表格的实例演示教程详解 前言 图片是Word的一种特殊内容,这篇文章主要介绍了关于Python操作word文档,向里面插入图片和表格的相关内容,下面话不多 ...

  6. python操作word文档中的图片_Python操作word文档插入图片和表格的实例演示

    前言P6Q免费资源网 图片是Word的一种特殊内容,这篇文章主要介绍了关于Python操作word文档,向里面插入图片和表格的相关内容,下面话不多说了,来一起看看详细的代码P6Q免费资源网 实例代码: ...

  7. java 实现word文档合并(支持文档中有图片和表格)

    1:maven <dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml&l ...

  8. java-制作flt模板,导出word文档带图片循环

    java-制作flt模板,导出word文档带图片循环 模板制作 制作xml 编辑xml文档 将xml模板转换为flt 编写工具类 导出word工具类 获取远程图片 使用示例 使用示例--springb ...

  9. html word 编辑表格,在Word文档中运用编辑表格的7个技巧

    来自:脚本之家 链接:http://www.jb51.net/office/word/466465.html 工作中经常用Word来写各类总结.方案.通告等文件,多数情况下都会文本表格并用.如何在Wo ...

最新文章

  1. Quartz2D在项目中的实际使用
  2. 理解 Delphi 的类(四) - 初识类的事件
  3. 一旦一个业务可以由一个人来全部完成而不涉及分工,就会产生单干的情况
  4. git 入门教程之协同开发
  5. 【深度学习的数学】绘制2×3×1层带sigmoid激活函数的神经网络感知机输出函数的三维图像(神经网络参数使用正态分布随机数)
  6. flink介绍:有界流和无界流
  7. MySQL 请选择合适的列!
  8. 智能计米器jk76怎么安装_Redmi智能电视X系列性能有多好?怎么安装第三方软件?...
  9. 【Android OpenGL ES 开发 (一)】使用c++开发opengles 与 日志功能 及 加载assets
  10. 硅谷大佬提前剧透未来!6本书,助你走在AI时代前沿
  11. Linux网络配置的基本方法
  12. 2019.08.29定时器以及轮播图
  13. python自动化办公真的好用吗-Python做什么更合适?|老男孩Python自动化运维
  14. RDP Wrapper
  15. pandownload网页版服务器维护中,PanDownload网页版源码
  16. mac 屏幕录制专家
  17. 【保姆级教程】STK3332系列环境光传感器整理!STK333X
  18. linux系统显示无法挂载,linux中的mount系统调用无法通过df命令显示文件系统的挂载点...
  19. 优客365网站导航开源版 v1.5.2
  20. 【DAPDM 四】--- dapm机制深入分析(上篇)

热门文章

  1. 超好用的word插件-工作和科研
  2. NO.0 QN9021 开发准备工作
  3. SIGCOMM 2022 Elasticity Detection:A Building Block for Internet Congestion Control
  4. 无线通信基础知识16:信号完整性
  5. 文件上传(三)阿里云上传文件
  6. java三国杀百度云,GitHub - wzk1015/sanguosha: 文字版三国杀,10000+行java实现
  7. Yolo配置与运行(github上下载的文件运行办法)
  8. 服务器的系统和NAS有啥区别,nas和云服务器区别
  9. Java线程池原理和使用
  10. 烟道机器人_烟道气体流速流量检测爬壁机器人设计