操作word
package com.gwt.flow.task; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import org.apache.commons.lang3.StringUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFPicture;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTabStop;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTabJc;
import org.springframework.beans.factory.annotation.Value; /**
* 通过word模板生成新的word工具类
*
* @author
*
*/
public class WorderToNewWordUtils extends XWPFDocument{ /**
* 根据模板生成新word文档
* 判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入
* @param inputUrl 模板存放地址
* @param outPutUrl 新文档存放地址
* @param textMap 需要替换的信息集合
* @param tableList 需要插入的表格信息集合
* @return 成功返回true,失败返回false
*
*
*
*/
public static boolean changWord(String inputUrl, String outputUrl,
Map<String, Object> textMap, List<String[]> tableList,String picturePath) {
//
// int index=outputUrl.indexOf("/");
// System.out.println(index);
// //根据第一个点的位置 获得第二个点的位置
// index=outputUrl.indexOf("/", index+1);
// //根据第二个点的位置,截取 字符串。得到结果 result
// String result=outputUrl.substring(0,index+1);
String result =picturePath;
//模板转换默认成功
boolean changeFlag = true;
try {
//获取docx解析对象
// XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
CustomXWPFDocument document = null;
OPCPackage pack = POIXMLDocument.openPackage(inputUrl);
document = new CustomXWPFDocument(pack);
//WorderToNewWordUtils.changePicture(document, textMap);
//解析替换文本段落对象
WorderToNewWordUtils.changeText(document, textMap,result);
//解析替换表格对象
WorderToNewWordUtils.changeTable(document, textMap, tableList);
//生成新的word
File file = new File(outputUrl);
if (file.exists()) {
file.delete();
}
FileOutputStream stream = new FileOutputStream(file);
document.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
changeFlag = false;
}
return changeFlag; } static String[] addBreaks ={
"${capLowTitle}",
"${resistHighTitle}",
"${signTitle}",
"${rectificationCapLow}",
"${rectificationResistHigh}",
"${rectificationSign}"
}; static String[] defFont ={
"${companyAndAddr}",
"${referenceHelpA}",
"${referenceHelpB}"
}; /**
* 替换段落文本
* @param document docx解析对象
* @param textMap 需要替换的信息集合
*/
public static void changeText(XWPFDocument document, Map<String, Object> textMap,String picturePath){
//获取段落集合
List<XWPFParagraph> paragraphs = document.getParagraphs(); for (XWPFParagraph paragraph : paragraphs) {
//判断此段落时候需要进行替换
String text = paragraph.getText();
if(checkText(text)){ List<XWPFRun> runs = paragraph.getRuns();
// for (XWPFRun run : runs) {
for (int i=0; i<runs.size(); i++) {
XWPFRun run = runs.get(i);
//run.setFontFamily("宋体");
List<String> defFontList = Arrays.asList(defFont);
if(run.toString().equals("${vol_bight}")) {
run.setFontSize(7);
}else if(!defFontList.contains(run.toString())){
//run.setFontSize(8);
}
String flag= new String(run.toString());
//System.out.println("段落的改变---》"+run.toString());
//替换模板原来位置
System.out.println(flag);
run.setText(changeValue(run.toString(), textMap), 0);
if(flag.equals("${imag}")) {
try {
XWPFRun run2 = paragraph.createRun();
paragraph.setAlignment(ParagraphAlignment.LEFT);
String imgFile =picturePath+"imgA_1.png";
FileInputStream is2 = new FileInputStream(imgFile);
run2.addPicture(is2, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(400), Units.toEMU(140));
XWPFRun run3 = paragraph.createRun();
run3.setBold(true);
paragraph.setAlignment(ParagraphAlignment.RIGHT);
String imgFile1 =picturePath+"imgA_2.png";
FileInputStream is3 = new FileInputStream(imgFile1);
run3.addPicture(is3, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(400), Units.toEMU(140));
run.addBreak();//换行
XWPFRun run4 = paragraph.createRun();
run4.setBold(true);
paragraph.setAlignment(ParagraphAlignment.LEFT);
String imgFile4 =picturePath+"imgA_3.png";
FileInputStream is4 = new FileInputStream(imgFile4);
run3.addPicture(is4, XWPFDocument.PICTURE_TYPE_JPEG, imgFile4, Units.toEMU(400), Units.toEMU(140)); XWPFRun run5 = paragraph.createRun();
paragraph.setAlignment(ParagraphAlignment.RIGHT);
String imgFile5 =picturePath+"imgA_4.png";
FileInputStream is5 = new FileInputStream(imgFile5);
run3.addPicture(is5, XWPFDocument.PICTURE_TYPE_JPEG, imgFile5, Units.toEMU(400), Units.toEMU(140)); XWPFRun run6 = paragraph.createRun();
paragraph.setAlignment(ParagraphAlignment.LEFT);
String imgFile6 =picturePath+"imgA_5.png";
FileInputStream is6 = new FileInputStream(imgFile6);
run3.addPicture(is6, XWPFDocument.PICTURE_TYPE_JPEG, imgFile6, Units.toEMU(400), Units.toEMU(140)); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(flag.equals("${imag2}")){
try {
XWPFRun run2 = paragraph.createRun();
paragraph.setAlignment(ParagraphAlignment.LEFT);
String imgFile =picturePath+"imgB_1.png";
FileInputStream is2 = new FileInputStream(imgFile);
run2.addPicture(is2, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(150), Units.toEMU(100)); XWPFRun run3 = paragraph.createRun();
run3.setBold(true);
paragraph.setAlignment(ParagraphAlignment.RIGHT);
String imgFile1 =picturePath+"imgB_2.png";
FileInputStream is3 = new FileInputStream(imgFile1);
run3.addPicture(is3, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(400), Units.toEMU(140));
run3.addBreak();//换行 XWPFRun run4 = paragraph.createRun();
paragraph.setAlignment(ParagraphAlignment.LEFT);
String imgFile4 =picturePath+"imgB_3.png";
FileInputStream is4 = new FileInputStream(imgFile4);
run4.addPicture(is4, XWPFDocument.PICTURE_TYPE_JPEG, imgFile4, Units.toEMU(400), Units.toEMU(140)); XWPFRun run6 = paragraph.createRun();
paragraph.setAlignment(ParagraphAlignment.RIGHT);
String imgFile6 =picturePath+"imgB_4.png";
FileInputStream is6 = new FileInputStream(imgFile6);
run6.addPicture(is6, XWPFDocument.PICTURE_TYPE_JPEG, imgFile6, Units.toEMU(400), Units.toEMU(140)); XWPFRun run7 = paragraph.createRun();
paragraph.setAlignment(ParagraphAlignment.LEFT);
String imgFile7 =picturePath+"imgB_5.png";
FileInputStream is7 = new FileInputStream(imgFile7);
run6.addPicture(is7, XWPFDocument.PICTURE_TYPE_JPEG, imgFile7, Units.toEMU(400), Units.toEMU(140)); } catch (Exception e) {
e.printStackTrace();
}
}
else if(flag.equals("${imag3}")){
try {
XWPFRun run2 = paragraph.createRun();
paragraph.setAlignment(ParagraphAlignment.LEFT);
String imgFile =picturePath+"imgC_1.png";
FileInputStream is2 = new FileInputStream(imgFile);
run2.addPicture(is2, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(400), Units.toEMU(140)); XWPFRun run3 = paragraph.createRun();
run3.setBold(true);
paragraph.setAlignment(ParagraphAlignment.RIGHT);
String imgFile1 =picturePath+"imgC_2.png";
FileInputStream is3 = new FileInputStream(imgFile1);
run3.addPicture(is3, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(400), Units.toEMU(140));
run3.addBreak();//换行 XWPFRun run4 = paragraph.createRun();
paragraph.setAlignment(ParagraphAlignment.LEFT);
String imgFile4 =picturePath+"imgC_3.png";
FileInputStream is4 = new FileInputStream(imgFile4);
run4.addPicture(is4, XWPFDocument.PICTURE_TYPE_JPEG, imgFile4, Units.toEMU(400), Units.toEMU(140));
} catch (Exception e) {
e.printStackTrace();
}
}
else if(flag.equals("${imag4}")){
try {
XWPFRun run2 = paragraph.createRun();
paragraph.setAlignment(ParagraphAlignment.LEFT);
String imgFile =picturePath+"imgD_1.png";
FileInputStream is2 = new FileInputStream(imgFile);
run2.addPicture(is2, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(400), Units.toEMU(140)); XWPFRun run3 = paragraph.createRun();
run3.setBold(true);
paragraph.setAlignment(ParagraphAlignment.RIGHT);
String imgFile1 =picturePath+"imgD_2.png";
FileInputStream is3 = new FileInputStream(imgFile1);
run3.addPicture(is3, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(400), Units.toEMU(140));
run3.addBreak();//换行 XWPFRun run4 = paragraph.createRun();
paragraph.setAlignment(ParagraphAlignment.LEFT);
String imgFile4 =picturePath+"imgD_3.png";
FileInputStream is4 = new FileInputStream(imgFile4);
run4.addPicture(is4, XWPFDocument.PICTURE_TYPE_JPEG, imgFile4, Units.toEMU(400), Units.toEMU(140));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} } /**
* 添加图片
* @param document docx解析对象
* @param textMap 需要替换的信息集合
*/
public static List<FileInputStream> changePicture(CustomXWPFDocument doc, Map<String, Object> map,FileInputStream in1,FileInputStream in2,FileInputStream in3){
List<FileInputStream> inputStreams = new ArrayList<>();
//获取段落集合
List<XWPFParagraph> paragraphs = doc.getParagraphs();
String type = (String) map.get("type");//图片的格式png,jpg
int width = Integer.parseInt((String) map.get("width"));//宽度
int high = Integer.parseInt((String) map.get("high"));//宽度 try { for (XWPFParagraph paragraph : paragraphs) {
String text = paragraph.getText();
if(checkText(text)){
if(text!=null) {
int indexOf = text.indexOf("img");
if(indexOf != -1){
//特殊处理图片
int length = paragraph.getRuns().size();
//将原有的Run去掉
if (length > 0) {
for (int i = (length - 1); i >= 0; i--) {
paragraph.removeRun(i);
}
}
}
//解析A图片
if(text.indexOf("${imgA_1}") != -1) {
String pictureUrl_A_1 = (String) map.get("imgA_1");
if(pictureUrl_A_1 != null) {
in1 = new FileInputStream(new File(pictureUrl_A_1));
String blipId = doc.addPictureData(in1, getPictureType(type));
doc.createPicture(blipId,doc.getNextPicNameNumber(getPictureType(type)), width, high,paragraph);
inputStreams.add(in1);
}
}
if(text.indexOf("${imgA_2}") != -1) {
String pictureUrl_A_2 = (String) map.get("imgA_2");
if(pictureUrl_A_2 != null) {
in2 = new FileInputStream(new File(pictureUrl_A_2));
String blipId = doc.addPictureData(in2, getPictureType(type));
doc.createPicture(blipId,doc.getNextPicNameNumber(getPictureType(type)), width, high,paragraph);
inputStreams.add(in2);
}
}
//解析B图片
if(text.indexOf("${imgB_1}") != -1) {
String pictureUrl_B_1 = (String) map.get("imgB_1");
if(pictureUrl_B_1 != null) {
high = 450;
in3 = new FileInputStream(new File(pictureUrl_B_1));
String blipIdb = doc.addPictureData(in3, getPictureType(type));
doc.createPicture(blipIdb,doc.getNextPicNameNumber(getPictureType(type)), width, high,paragraph);
inputStreams.add(in3);
}
}
}
} //判断此段落时候需要进行替换
// String text = paragraph.getText();
// if(checkText(text)){
// List<XWPFRun> runs = paragraph.getRuns();
// for (XWPFRun run : runs) {
// System.out.println("加载图片---》"+run.toString());
// String pName =run.toString().substring(run.toString().indexOf("{")+1, run.toString().length()-1);
// try {
// //if(run.toString().equals("${"+pName+"}")) {
// String text2 = run.getText(0);
//
// if (text2 != null) {
//
// if (text2.indexOf("${"+pName+"}") >= 0) {
// //String pictureUrl="E:\\ABC\\"+ pName + ""+type;
// String pictureUrl = Constant.TEMPLETE_PATH + pName + ".png";
//// run.addBreak();
//// run.addPicture(new FileInputStream(pictureUrl),getPictureType(type),pictureUrl, Units.toEMU(width),Units.toEMU(high)); // 宽200x高200 pixels
//// run.addBreak(BreakType.PAGE);
// int length = paragraph.getRuns().size();
// //将原有的Run去掉
// if (length > 0) {
// for (int i = (length - 1); i >= 0; i--) {
// paragraph.removeRun(i);
// }
// }
// String blipId = doc.addPictureData(new FileInputStream(new File(pictureUrl)), getPictureType(type));
// doc.createPicture(blipId,doc.getNextPicNameNumber(getPictureType(type)), width, high,paragraph);
// break;
// //}
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
} } catch (Exception e) {
e.printStackTrace();
}
return inputStreams; } /**
* 替换表格对象方法
* @param document docx解析对象
* @param textMap 需要替换的信息集合
* @param tableList 需要插入的表格信息集合
*/
public static void changeTable(XWPFDocument document, Map<String, Object> textMap,
List<String[]> tableList){
//获取表格对象集合
List<XWPFTable> tables = document.getTables(); for (int i = 0; i < tables.size(); i++) {
//只处理行数大于等于2的表格,且不循环表头
XWPFTable table = tables.get(i);
if(table.getRows().size()>0){
//判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入
if(checkText(table.getText())){
List<XWPFTableRow> rows = table.getRows();
//System.out.println("替换的信息--"+textMap.get("dischargeDate"));
//遍历表格,并替换模板
eachTable(rows, textMap);
}else{
// System.out.println("插入"+table.getText());
//insertTable(table, tableList);
}
}
}
}
/**
* 遍历表格
* @param rows 表格行对象
* @param textMap 需要替换的信息集合
*/
public static void eachTable(List<XWPFTableRow> rows ,Map<String, Object> textMap){
for (XWPFTableRow row : rows) {
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
//判断单元格是否需要替换
if(checkText(cell.getText())){
List<XWPFParagraph> paragraphs = cell.getParagraphs();
for (XWPFParagraph paragraph : paragraphs) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
//run.setFontFamily("宋体");
if(run.toString().indexOf("${dischargeDate}")>=0) {
//run.setBold(true);加粗
//run.setColor("FF0000");//红色
//run.setFontSize(5);//字体大小
} //System.out.println(run.toString());
String value = changeValue(run.toString(), textMap);
List<String> asList = Arrays.asList(addBreaks);
if (StringUtils.isNoneBlank(value) && asList.contains(run.toString())) {
run.setText(value, 0);
// run.addBreak();
}else {
run.setText(value, 0);
}
}
}
}
}
}
} public void createPicture(String blipId,int id, int width, int height, XWPFParagraph paragraph)
{
final int EMU = 9525;
width *= EMU;
height *= EMU;
// String blipId = getAllPictures().get(id).getPackageRelationship().getId(); //CTInline inline = createParagraph().createRun().getCTR().addNewDrawing().addNewInline();
//给段落插入图片
CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline(); String picXml = "" +
"<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +
" <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
" <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
" <pic:nvPicPr>" +
" <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" +
" <pic:cNvPicPr/>" +
" </pic:nvPicPr>" +
" <pic:blipFill>" +
" <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +
" <a:stretch>" +
" <a:fillRect/>" +
" </a:stretch>" +
" </pic:blipFill>" +
" <pic:spPr>" +
" <a:xfrm>" +
" <a:off x=\"0\" y=\"0\"/>" +
" <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" +
" </a:xfrm>" +
" <a:prstGeom prst=\"rect\">" +
" <a:avLst/>" +
" </a:prstGeom>" +
" </pic:spPr>" +
" </pic:pic>" +
" </a:graphicData>" +
"</a:graphic>"; //CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData();
XmlToken xmlToken = null;
try
{
xmlToken = XmlToken.Factory.parse(picXml);
}
catch(XmlException xe)
{
xe.printStackTrace();
}
inline.set(xmlToken);
//graphicData.set(xmlToken); inline.setDistT(0);
inline.setDistB(0);
inline.setDistL(0);
inline.setDistR(0); CTPositiveSize2D extent = inline.addNewExtent();
extent.setCx(width);
extent.setCy(height); CTNonVisualDrawingProps docPr = inline.addNewDocPr();
docPr.setId(id);
docPr.setName("Picture " + id);
docPr.setDescr("Generated");
} /**
* 为表格插入数据,行数不够添加新行
* @param table 需要插入数据的表格
* @param tableList 插入数据集合
*/
public static void insertTable(XWPFTable table, List<String[]> tableList){
//创建行,根据需要插入的数据添加新行,不处理表头
for(int i = 1; i < tableList.size(); i++){
XWPFTableRow row =table.createRow();
}
//遍历表格插入数据
List<XWPFTableRow> rows = table.getRows();
for(int i = 1; i < rows.size(); i++){
XWPFTableRow newRow = table.getRow(i);
List<XWPFTableCell> cells = newRow.getTableCells();
for(int j = 0; j < cells.size(); j++){
XWPFTableCell cell = cells.get(j);
cell.setText(tableList.get(i-1)[j]);
}
} } /**
* 判断文本中时候包含$
* @param text 文本
* @return 包含返回true,不包含返回false
*/
public static boolean checkText(String text){
boolean check = false;
if(text == null) {
return true;
}
if(text.indexOf("$")!= -1){
check = true;
}
return check;
} /**
* 匹配传入信息集合与模板
* @param value 模板需要替换的区域
* @param textMap 传入信息集合
* @return 模板需要替换区域信息集合对应值
*/
public static String changeValue(String value, Map<String, Object> textMap){
Set<Entry<String, Object>> textSets = textMap.entrySet(); for (Entry<String, Object> textSet : textSets) {
//匹配模板与替换值 格式${key}
String key = "${"+textSet.getKey()+"}";
if(value.indexOf(key)!= -1){
value = (String) textSet.getValue();
break;
}
}
//模板未匹配到区域替换为空
if(checkText(value)){
value = "";
}
return value;
} /**
* 根据图片类型,取得对应的图片类型代码
* @param picType
* @return int
*/
public static int getPictureType(String picType){
int res = XWPFDocument.PICTURE_TYPE_PICT;
if(picType != null){
if(picType.equalsIgnoreCase("png")){
res = XWPFDocument.PICTURE_TYPE_PNG;
}else if(picType.equalsIgnoreCase("dib")){
res = XWPFDocument.PICTURE_TYPE_DIB;
}else if(picType.equalsIgnoreCase("emf")){
res = XWPFDocument.PICTURE_TYPE_EMF;
}else if(picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")){
res = XWPFDocument.PICTURE_TYPE_JPEG;
}else if(picType.equalsIgnoreCase("wmf")){
res = XWPFDocument.PICTURE_TYPE_WMF;
}
}
return res;
} public static void addHeader(CustomXWPFDocument doc,String imgFile) {
try {
// XWPFDocument doc= new XWPFDocument(); // the body content
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run=paragraph.createRun();
// run.setText("The Body:"); // paragraph = doc.createParagraph();
// run=paragraph.createRun();
// run.setText("Lorem ipsum...."); // create header start
CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(doc, sectPr); XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT); paragraph = header.getParagraphArray(0);
paragraph.setAlignment(ParagraphAlignment.LEFT); CTTabStop tabStop = paragraph.getCTP().getPPr().addNewTabs().addNewTab();
tabStop.setVal(STTabJc.RIGHT);
int twipsPerInch = 1440;
tabStop.setPos(BigInteger.valueOf(6 * twipsPerInch)); // run = paragraph.createRun();
// run.setText("The Header:");
// run.addTab(); run = paragraph.createRun();
// String imgFile="E:\\ABC\\logo.png";
XWPFPicture picture = run.addPicture(new FileInputStream(imgFile), XWPFDocument.PICTURE_TYPE_PNG, imgFile, Units.toEMU(250), Units.toEMU(50));
System.out.println(picture); //XWPFPicture is added
System.out.println(picture.getPictureData()); //but without access to XWPFPictureData (no blipID) String blipID = "";
for(XWPFPictureData picturedata : header.getAllPackagePictures()) {
blipID = header.getRelationId(picturedata);
System.out.println(blipID); //the XWPFPictureData are already there
}
picture.getCTPicture().getBlipFill().getBlip().setEmbed(blipID); //now they have a blipID also
System.out.println(picture.getPictureData()); // create footer start
// XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT); // paragraph = footer.getParagraphArray(0);
paragraph.setAlignment(ParagraphAlignment.RIGHT); // run = paragraph.createRun();
// run.setText("The Footer:"); //doc.write(new FileOutputStream("E:\\ABC\\test.docx")); }catch (Exception e) {
e.printStackTrace();
}
} /**
* 创建目录
* @param basePath "E:/ABC/word/"
*/
public static void createDir(String basePath)
{
File file = new File(basePath);
if (!file.exists())
file.mkdirs();
} public static void main(String[] args) {
//模板文件地址
String inputUrl = "E:\\ABC\\001.docx";
//新生产的模板文件
String outputUrl = "E:\\ABC\\test.docx"; Map<String, String> testMap = new HashMap<String, String>();
testMap.put("name", "小明");
testMap.put("sex", "男");
testMap.put("address", "软件园");
testMap.put("phone", "88888888");
testMap.put("high", "200");
testMap.put("width", "200");
testMap.put("imgA", "E:\\ABC\\imgA.png");
testMap.put("imgB", "E:\\ABC\\imgB.png");
List<String[]> testList = new ArrayList<String[]>();
testList.add(new String[]{"1","1AA","1BB","1CC"});
testList.add(new String[]{"2","2AA","2BB","2CC"});
testList.add(new String[]{"3","3AA","3BB","3CC"});
testList.add(new String[]{"4","4AA","4BB","4CC"});
// WorderToNewWordUtils.changWord(inputUrl, outputUrl, testMap, testList); // try {
// // XWPFDocument doc= new XWPFDocument();
// CustomXWPFDocument doc = null;
// OPCPackage pack = POIXMLDocument.openPackage("E:\\ABC\\001.docx");
// doc = new CustomXWPFDocument(pack);
//
// // the body content
// XWPFParagraph paragraph = doc.createParagraph();
// XWPFRun run=paragraph.createRun();
//// run.setText("The Body:");
//
//// paragraph = doc.createParagraph();
//// run=paragraph.createRun();
//// run.setText("Lorem ipsum....");
//
// // create header start
// CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
// XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(doc, sectPr);
//
// XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);
//
// paragraph = header.getParagraphArray(0);
// paragraph.setAlignment(ParagraphAlignment.LEFT);
//
// CTTabStop tabStop = paragraph.getCTP().getPPr().addNewTabs().addNewTab();
// tabStop.setVal(STTabJc.RIGHT);
// int twipsPerInch = 1440;
// tabStop.setPos(BigInteger.valueOf(6 * twipsPerInch));
//
//// run = paragraph.createRun();
//// run.setText("The Header:");
//// run.addTab();
//
// run = paragraph.createRun();
// String imgFile="E:\\ABC\\logo.png";
// XWPFPicture picture = run.addPicture(new FileInputStream(imgFile), XWPFDocument.PICTURE_TYPE_PNG, imgFile, Units.toEMU(250), Units.toEMU(50));
// System.out.println(picture); //XWPFPicture is added
// System.out.println(picture.getPictureData()); //but without access to XWPFPictureData (no blipID)
//
// String blipID = "";
// for(XWPFPictureData picturedata : header.getAllPackagePictures()) {
// blipID = header.getRelationId(picturedata);
// System.out.println(blipID); //the XWPFPictureData are already there
// }
// picture.getCTPicture().getBlipFill().getBlip().setEmbed(blipID); //now they have a blipID also
// System.out.println(picture.getPictureData());
//
//
// // create footer start
//// XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
////
//// paragraph = footer.getParagraphArray(0);
// paragraph.setAlignment(ParagraphAlignment.RIGHT);
////
//// run = paragraph.createRun();
//// run.setText("The Footer:");
//
//
// doc.write(new FileOutputStream("E:\\ABC\\test333.docx"));
//
// }catch (Exception e) {
// e.printStackTrace();
// }
}
}
生成图片
package com.gwt.utils; import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID; 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.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.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils; import com.gwt.flow.entity.Advice;
import com.gwt.flow.entity.Report;
import com.gwt.flow.mapper.ReportMapper;
import com.gwt.flow.model.SPersonCreditModel;
import com.gwt.flow.service.AdviceService;
import com.gwt.flow.service.OlpayInfoService;
import com.gwt.flow.service.ReportService;
import com.gwt.flow.service.SAppointService;
import com.gwt.flow.service.SPersonCreditService;
import com.gwt.flow.service.SPzinfoService;
import com.gwt.flow.service.UpdateGeneratewordService;
import com.gwt.flow.task.WorderToNewWordUtils;
import com.gwt.utils.JfreeChartUtils;
@Service
public class UpdateGeneratewordimpl implements UpdateGeneratewordService { //private String picturePath="D:/ObjectTemp/"; @Value("${web.upload-path}")
private String picturePath;
private String annotation="";
@Autowired
private SAppointService sAppointService;
@Autowired
private AdviceService adviceService; @Autowired
private OlpayInfoService olpayInfoService;
@Autowired
private SPersonCreditService sPersonCreditService; @Autowired
private SPzinfoService sPzinfoService; @Autowired
ReportMapper reportmapper; @Autowired
ReportService reportService;
Map<String, Object> params = new HashMap<String, Object>(); DecimalFormat df = new DecimalFormat("0.00");
@Override
public void Generateword(String mouth) throws Exception {
createImgA1(mouth);
createImgA2(mouth);
createImgA3(mouth);
createImgA4(mouth);
createImgA5(mouth);
createImgB1(mouth);
createImgB2(mouth);
createImgB3(mouth);
createImgB4(mouth);
createImgB5(mouth);
createImgC2(mouth);
createImgC3(mouth);
createImgD1(mouth);
createImgD2(mouth);
getCreditBasicStatistic(mouth); //修改了6个sql
Map<String, Object> schoolQuitStatistic = sAppointService.getSchoolQuitStatistic(mouth);
double allQuitCount=Double.valueOf(schoolQuitStatistic.get("allQuitCount").toString());
double allApointCount=Double.valueOf(schoolQuitStatistic.get("allApointCount").toString());
// System.out.println("退单率为 "+getPercentage(allQuitCount,allApointCount));
double allQuitPersonCount=Double.valueOf(schoolQuitStatistic.get("allQuitPersonCount").toString());
double allPersonCount=Double.valueOf(schoolQuitStatistic.get("allPersonCount").toString());
// System.out.println("退单人数占比 "+getPercentage(allQuitPersonCount,allPersonCount));
double pre2AllQuitCount=Double.valueOf(schoolQuitStatistic.get("pre2AllQuitCount").toString());
double pre2AllApointCount=Double.valueOf(schoolQuitStatistic.get("pre2AllApointCount").toString());
double result=(((allQuitCount/allApointCount)-(pre2AllQuitCount/pre2AllApointCount))/(pre2AllQuitCount/pre2AllApointCount))*100;
///System.out.println("退单率月环比 "+String.format("%.2f", result));
String quitMonthAddRate= String.format("%.2f", result)+"%";
//修改sql like
List<Map<String, Object>> quitTypePre10 = sAppointService.getQuitTypePre10(mouth);
for(int i=0; i<quitTypePre10.size(); i++) {
Map<String, Object> map = quitTypePre10.get(i);
if(map.get("QUIT_TYPE")==null) {
map.put("QUIT_TYPE", "无匹配数据");
}
}
//意见和建议 //不变
List<Advice> adiviceList=adviceService.find();
//全校资金支付失败类型排行榜 //修改sql
List<Map<String, Object>> payFailTypePre5 = olpayInfoService.getPayFailTypePre5(mouth);
for(int i=0; i<payFailTypePre5.size(); i++) {
Map<String, Object> map = payFailTypePre5.get(i);
if(map.get("QRY_MSG")==null) {
map.put("QRY_MSG", "无匹配数据");
}
System.out.println(map.get("QRY_MSG"));
System.out.println(map.get("NUMS"));
}
params.put("a_1", schoolQuitStatistic.get("allApointCount").toString()); //提交预约单数
params.put("a_2", schoolQuitStatistic.get("allQuitCount").toString()); //退单数
params.put("a_3", getPercentage(allQuitCount,allApointCount).toString()); //退单率
params.put("a_4", schoolQuitStatistic.get("allQuitPersonCount").toString()); //退单涉及人数
params.put("a_5", getPercentage(allQuitPersonCount,allPersonCount).toString()); //退单人数占比
params.put("a_6", quitMonthAddRate.toString()); //月环比 params.put("b_1", quitTypePre10.get(0).get("QUIT_TYPE").toString());
params.put("b_11", quitTypePre10.get(0).get("NUMS").toString());
params.put("b2", quitTypePre10.get(1).get("QUIT_TYPE").toString());
params.put("b21", quitTypePre10.get(1).get("NUMS").toString());
params.put("b3", quitTypePre10.get(2).get("QUIT_TYPE").toString());
params.put("b31", quitTypePre10.get(2).get("NUMS").toString());
params.put("b4", quitTypePre10.get(3).get("QUIT_TYPE").toString());
params.put("b41", quitTypePre10.get(3).get("NUMS").toString());
params.put("b5", quitTypePre10.get(4).get("QUIT_TYPE").toString());
params.put("b51", quitTypePre10.get(4).get("NUMS").toString());
params.put("b6", quitTypePre10.get(5).get("QUIT_TYPE").toString());
params.put("b61", quitTypePre10.get(5).get("NUMS").toString());
params.put("b7", quitTypePre10.get(6).get("QUIT_TYPE").toString());
params.put("b71", quitTypePre10.get(6).get("NUMS").toString());
params.put("b_8", quitTypePre10.get(7).get("QUIT_TYPE").toString());
params.put("b81", quitTypePre10.get(7).get("NUMS").toString());
params.put("b9", quitTypePre10.get(8).get("QUIT_TYPE").toString());
params.put("b91", quitTypePre10.get(8).get("NUMS").toString());
params.put("b_10", quitTypePre10.get(9).get("QUIT_TYPE").toString());
params.put("b_101", quitTypePre10.get(9).get("NUMS").toString()); params.put("c1", adiviceList.get(0).getConsultation().toString());
params.put("c_1", adiviceList.get(0).getAdvice().toString());
params.put("c2", adiviceList.get(1).getConsultation().toString());
params.put("c_2", adiviceList.get(1).getAdvice().toString());
params.put("c3", adiviceList.get(2).getConsultation().toString());
params.put("c_3", adiviceList.get(2).getAdvice().toString());
params.put("c4", adiviceList.get(3).getConsultation().toString());
params.put("c_4", adiviceList.get(3).getAdvice().toString()); for(int i=0; i<payFailTypePre5.size(); i++) {
Map<String, Object> map = payFailTypePre5.get(i);
int j=i+1;
params.put("d_"+j, map.get("QRY_MSG").toString());
params.put("d_"+j+"1", map.get("NUMS").toString());
}
//财务工作情况
Map<String, Object> map=checkTotal(mouth);
//附件总数
params.put("e1", map.get("fileTotal").toString());
//制单总数
params.put("e2", map.get("inputTotal").toString());
//制单总数
params.put("e3", map.get("checkTotal").toString());
//人均制单数
params.put("e4", map.get("avgInput").toString());
//人均复核数
params.put("e5", map.get("avgCheck").toString());
//平均分配时间(min)
params.put("e6", map.get("avgDistribute").toString());
//平均处理时间(h)
params.put("e7", map.get("avgManageTime").toString());
//月平均处理单据效率
params.put("e8", map.get("avgManageTimeEfficet").toString());
System.out.println(map.get("avgDistribute").toString());
System.out.println(map.get("avgManageTimeEfficet").toString());
//月环比
params.put("e9", map.get("addPercent").toString());
String filePath = "/static/报告WORD模板6.docx";
try {
UUID uuid = UUID.randomUUID();
String filesrc=picturePath+uuid+"报告WORD模板.docx";
WorderToNewWordUtils.changWord(ResourceUtils.getURL("classpath:").getPath()+filePath,filesrc,params,null,picturePath);
Report report=new Report();
report.setFilesrc(filesrc);
report.setFilename("学校月度报销综合报告");
report.setFilemouth(mouth);
List<Report> list=reportmapper.selectByReport(report);
if(list.size()>0) {
reportmapper.updateByPrimaryKeySelective(report);
}
else {
reportService.save(report);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//求百分比 public void getCreditBasicStatistic(String mouth){
//不变
double avgCreditScore = sPersonCreditService.getAvgCreditScore();
double maxCreditScore = sPersonCreditService.getMaxCreditScore();
double minCreditScore = sPersonCreditService.getMinCreditScore();
//平均分数
params.put("g1", df.format(avgCreditScore).toString());
//最高分数
params.put("g2", String.valueOf(maxCreditScore));
//最低分数
params.put("g3", String.valueOf(minCreditScore));
} public Map<String, Object> checkTotal(String mouth) throws ParseException {
SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM");
Calendar cal = Calendar.getInstance();
Date date=dft.parse(mouth);
cal.setTime(date);
String month = dft.format(cal.getTime());
Map<String, Object> map = new HashMap<String, Object>();
map.put("month", month);
long fileTotal = sPzinfoService.getFileTotal(map);
long inputTotal = sPzinfoService.getInputTotal(map);
map.put("isCheck", "true");
long checkTotal = sPzinfoService.getInputTotal(map);
long inputPersonNum = sPzinfoService.getInputPersonNum(map);
long checkPersonNum = sPzinfoService.getCheckPersonNum(map);
double avgDistribute = sPzinfoService.getAvgDistribute(map);
double avgManageTime = sPzinfoService.getAvgManageTime(map);
//查找复核人权重
double weigth_Check=sPzinfoService.getWeigthForCheck(mouth);
//查找制单人权重
double weigth_input=sPzinfoService.getWeigthForinput(mouth);
// 上月
cal.add(cal.MONTH, -1);
String preMonth = dft.format(cal.getTime());
map.put("month", preMonth);
double preAvgManageTime = sPzinfoService.getAvgManageTime(map);
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("fileTotal", fileTotal);
resultMap.put("inputTotal", inputTotal);
resultMap.put("checkTotal", checkTotal);
try {
double avgInput;
if(weigth_input>0) {
avgInput=inputTotal/weigth_input;
}else {
avgInput = inputTotal / inputPersonNum;
}
resultMap.put("avgInput", avgInput);
} catch (Exception e) {
resultMap.put("avgInput", 0);
}
try {
double check;
if(weigth_Check>0) {
check = checkTotal / weigth_Check;
}else {
check = checkTotal / checkPersonNum;
}
resultMap.put("avgCheck", check);
} catch (Exception e) {
resultMap.put("avgCheck", 0);
}
//平均分配时间
resultMap.put("avgDistribute", df.format(avgDistribute*60));
//平均处理时间(h)
resultMap.put("avgManageTime", df.format(avgManageTime)); resultMap.put("preAvgManageTime", preAvgManageTime);
//月平均处理单据效率
resultMap.put("avgManageTimeEfficet", df.format(preAvgManageTime/60));
//月环比
String addPercent= df.format((preAvgManageTime-avgManageTime)*100/60)+"%";
resultMap.put("addPercent", addPercent); //生成图片c1
DefaultCategoryDataset ds2= new DefaultCategoryDataset();
ds2.addValue( Double.valueOf(resultMap.get("avgDistribute").toString()) , "数据" ,"平均每单分配时间");
ds2.addValue( Double.valueOf(resultMap.get("avgManageTime").toString()) , "数据" ,"平均每单处理时间");
DefaultCategoryDataset capDataset2 = ds2;
String filePath2 = JfreeChartUtils.newInstance()
.setTiltle("平均每单分配/平均每单处理时间(h)")
.setLabel("占比", "")
.addAnnotation(annotation)
.setSize(JfreeChartUtils.large_width, JfreeChartUtils.large_heigh)
.generateBarChart(capDataset2, picturePath, "imgC_1"); return resultMap;
}
public String getPercentage(double number1,double number2) {
double temp = number1 / number2;
return Math.round((number1 / number2) * 10000) / 100.0 + "%";
}
public void createImgA1(String mouth) {
//sql没改改了传入的月份
List<Map<String, Object>> quitRateByMonth = sAppointService.getQuitRateByMonth(mouth);
DefaultCategoryDataset line_chart_dataset = new DefaultCategoryDataset();
for(int i=0; i<quitRateByMonth.size(); i++) {
Map<String, Object> map = quitRateByMonth.get(i);
line_chart_dataset.addValue( Double.valueOf(map.get("quitRate").toString()) , "月份" ,map.get("month").toString());
}
JFreeChart lineChartObject = ChartFactory.createLineChart(
"全校退单率月度统计","",
"占比",
line_chart_dataset,PlotOrientation.VERTICAL,
true,true,false);
CategoryPlot plot = (CategoryPlot) lineChartObject.getPlot();
plot.setBackgroundPaint(Color.WHITE);
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
Font kfont = new Font("宋体", Font.PLAIN, 18);
lineChartObject.getLegend().setItemFont(kfont);
plot.getDomainAxis().setLabelFont(kfont);
plot.getRangeAxis().setLabelFont(kfont);
lineChartObject.getTitle().setFont(kfont); LineAndShapeRenderer renderer = (LineAndShapeRenderer)plot.getRenderer();
DecimalFormat decimalformat1 = new DecimalFormat("##.##");//数据点显示数据值的格式
renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", decimalformat1));
renderer.setItemLabelsVisible(true);//设置项标签显示
renderer.setBaseItemLabelsVisible(true);//基本项标签显示
renderer.setShapesFilled(Boolean.TRUE);//在数据点显示实心的小图标
renderer.setShapesVisible(true);//设置显示小图标
int width = 857; /* Width of the image */
int height = 300; /* Height of the image */
try {
ChartUtilities.saveChartAsJPEG(new File(picturePath+"imgA_1.png") ,lineChartObject, width ,height);
} catch (IOException e) {
e.printStackTrace();
}
//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/jfreechart/jfreechart_line_chart.html
}
public void createImgA2(String mouth) {
//固定的图片
//全校退单率按类型统计
//List<Map<String, Object>> quitTypeRateNums = sAppointService.getQuitTypeRateNums();
//任务执行代码
DefaultCategoryDataset ds= new DefaultCategoryDataset();
ds.addValue( (double) 0.22222222, "数据"," 酬金业务");
ds.addValue((double) 0.2, "数据", "普通业务");
DefaultCategoryDataset capDataset = ds;
String filePath = JfreeChartUtils.newInstance()
.setTiltle("全校退单率按类型统计")
.setLabel("占比", "")
.addAnnotation(annotation)
.setSize(JfreeChartUtils.large_width, JfreeChartUtils.large_heigh)
.generateBarChart(capDataset, picturePath, "imgA_2");
}
public void createImgA3(String mouth) {
//退单率排行榜学院 修改了 sq了 like后
List<Map<String, Object>> quitRatePre5ByDept = sAppointService.getQuitRatePre5ByDept(mouth);
DefaultCategoryDataset ds2= new DefaultCategoryDataset();
for(int i=0; i<quitRatePre5ByDept.size(); i++) {
Map<String, Object> map = quitRatePre5ByDept.get(i);
System.out.println(map.get("QUITRATE"));
System.out.println(map.get("DEPT"));
ds2.addValue( Double.valueOf(map.get("QUITRATE").toString()) , "数据" ,map.get("DEPT").toString());
}
DefaultCategoryDataset capDataset2 = ds2;
String filePath2 = JfreeChartUtils.newInstance()
.setTiltle("退单率排行榜学院")
.setLabel("占比", "")
.addAnnotation(annotation)
.setSize(JfreeChartUtils.large_width, JfreeChartUtils.large_heigh)
.generateBarChart(capDataset2, picturePath, "imgA_3");
}
public void createImgA4(String mouth) {
//退单率排行榜实际报销人 修改了 sq了 like后
List<Map<String, Object>> quitRatePre5ByByPerson = sAppointService.getQuitRatePre5ByPerson(mouth);
DefaultCategoryDataset ds3= new DefaultCategoryDataset();
for(int i=0; i<quitRatePre5ByByPerson.size(); i++) {
Map<String, Object> map = quitRatePre5ByByPerson.get(i);
ds3.addValue( Double.valueOf(map.get("QUITRATE").toString()) , "数据" ,map.get("SUBMIT_PERSONNAME").toString());
}
DefaultCategoryDataset capDataset3 = ds3;
String filePath3 = JfreeChartUtils.newInstance()
.setTiltle("退单率排行榜(实际报销人)")
.setLabel("占比", "")
.addAnnotation(annotation)
.setSize(JfreeChartUtils.large_width, JfreeChartUtils.large_heigh)
.generateBarChart(capDataset3, picturePath, "imgA_4");
}
public void createImgA5(String mouth) {
//退单率排行榜负责人 修改了 sq了 like后
List<Map<String, Object>> RatePre5ByCharge = sAppointService.getQuitRatePre5ByCharge(mouth);
DefaultCategoryDataset ds4= new DefaultCategoryDataset();
for(int i=0; i<RatePre5ByCharge.size(); i++) {
Map<String, Object> map = RatePre5ByCharge.get(i);
ds4.addValue( Double.valueOf(map.get("QUITRATE").toString()) , "数据" ,map.get("USERNAME").toString());
}
DefaultCategoryDataset capDataset4 = ds4;
JfreeChartUtils.newInstance()
.setTiltle("退单率排行榜(负责人)")
.setLabel("占比", "")
.addAnnotation(annotation)
.setSize(JfreeChartUtils.large_width, JfreeChartUtils.large_heigh)
.generateBarChart(capDataset4, picturePath, "imgA_5");
}
public void createImgB1(String mouth) {
//修改impl 传入时间生成 日历
Map<String, Object> preAndPre2MonthData = olpayInfoService.getPreAndPre2MonthData(mouth);
Font font = new Font("宋体", Font.PLAIN, 18);
//如果不使用Font,中文将显示不出来
DefaultPieDataset pds = new DefaultPieDataset();
pds.setValue("失败", Double.valueOf(preAndPre2MonthData.get("prePayFailCount").toString()));
pds.setValue("成功", Double.valueOf(preAndPre2MonthData.get("prePayCount").toString())-Double.valueOf(preAndPre2MonthData.get("prePayFailCount").toString()));
JFreeChart chart = ChartFactory.createPieChart("失败率月环比", pds, true, false, true); //设置图片标题的字体
chart.getTitle().setFont(font);
//得到图块,准备设置标签的字体
PiePlot plot = (PiePlot) chart.getPlot();
//设置分裂效果,需要指定分裂出去的key
plot.setExplodePercent("天使-彦", 0.1);
//设置标签字体
plot.setLabelFont(font);
//设置图例项目字体
chart.getLegend().setItemFont(font);
plot.setStartAngle(new Float(3.14f / 2f));
//设置plot的前景色透明度
plot.setForegroundAlpha(0.7f);
//设置颜色
plot.setSectionPaint(0, new Color(0xF7, 0x79, 0xED));
//设置plot的背景色透明度
plot.setBackgroundAlpha(0.0f);
//设置标签生成器(默认{0})
//{0}:key {1}:value {2}:百分比 {3}:sum
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1})/{2}"));
try {
ChartUtilities.saveChartAsJPEG(new File(picturePath+"imgB_1.png"), chart, 500, 300);
} catch (IOException e) {
e.printStackTrace();
}
}
public void createImgB2(String mouth) {
//修改impl 传入时间生成 日历
List<Map<String, Object>> payFailMonthData = olpayInfoService.getPayFailMonthData(mouth);
DefaultCategoryDataset line_chart_dataset = new DefaultCategoryDataset();
for(int i=0; i<payFailMonthData.size(); i++) {
Map<String, Object> map = payFailMonthData.get(i);
System.out.println(map.get("month"));
System.out.println(map.get("quitRate"));
line_chart_dataset.addValue( Double.valueOf(map.get("payFailRate").toString()) , "月份" ,map.get("month").toString());
}
JFreeChart lineChartObject = ChartFactory.createLineChart(
"资金支付失败率月度统计(全校)","",
"占比",
line_chart_dataset,PlotOrientation.VERTICAL,
true,true,false);
CategoryPlot plot = (CategoryPlot) lineChartObject.getPlot();
plot.setBackgroundPaint(Color.WHITE);
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
Font kfont = new Font("宋体", Font.PLAIN, 18);
lineChartObject.getLegend().setItemFont(kfont);
plot.getDomainAxis().setLabelFont(kfont);
plot.getRangeAxis().setLabelFont(kfont); LineAndShapeRenderer renderer = (LineAndShapeRenderer)plot.getRenderer();
DecimalFormat decimalformat1 = new DecimalFormat("##.####");//数据点显示数据值的格式
renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", decimalformat1));
renderer.setItemLabelsVisible(true);//设置项标签显示
renderer.setBaseItemLabelsVisible(true);//基本项标签显示
renderer.setShapesFilled(Boolean.TRUE);//在数据点显示实心的小图标
renderer.setShapesVisible(true);//设置显示小图标
lineChartObject.getTitle().setFont(kfont);
int width = 500;
int height = 400;
try {
ChartUtilities.saveChartAsJPEG(new File(picturePath+"imgB_2.png") ,lineChartObject, width ,height);
} catch (IOException e) {
e.printStackTrace(); }
}
public void createImgB3(String mouth) {
//直接传入月份
Map<String, Object> m = new HashMap<String, Object>();
m.put("month", mouth);
List<Map<String, Object>> payFailRateByDept = olpayInfoService.getPayFailRateByDept(m); DefaultCategoryDataset ds2= new DefaultCategoryDataset();
for(int i=0; i<payFailRateByDept.size(); i++) {
Map<String, Object> map = payFailRateByDept.get(i);
System.out.println(map.get("QUITRATE"));
System.out.println(map.get("DEPT"));
ds2.addValue( Double.valueOf(map.get("FAILRATE").toString()) , "数据" ,map.get("DEPTNAME").toString());
}
DefaultCategoryDataset capDataset2 = ds2;
String filePath2 = JfreeChartUtils.newInstance()
.setTiltle("支付失败率排行榜(学院)")
.setLabel("占比", "")
.addAnnotation(annotation)
.setSize(JfreeChartUtils.large_width, JfreeChartUtils.large_heigh)
.generateBarChart(capDataset2, picturePath, "imgB_3");
}
public void createImgB4(String mouth) throws Exception {
//修改impl 传入时间生成 日历
Map<String, Object> payFailRateByDeptMonth = olpayInfoService.getPayFailRateByDeptMonth(mouth);
DefaultCategoryDataset line_chart_dataset = new DefaultCategoryDataset();
List<Map<String, Object>> list=(List<Map<String, Object>>) payFailRateByDeptMonth.get("rows");
for(int i=0;i<list.size();i++) {
Map<String, Object> map=list.get(i);
// System.out.println( map.get("体育部").toString());
if(map.containsKey("体育部")&&(map.get("体育部").toString()).indexOf("0")==-1) {
map.replace("体育部", 0);
}
//{学报编辑部=0.0000, month=2019-02, 通信抗干扰技术国家级重点实验室=0.0028, 格拉斯哥学院=0.0800, 党委保卫部(保卫处)=0.0000, 图书馆=0.0000} String key="";
String value="";
for (Entry<String, Object> entry : map.entrySet()) {
key = entry.getKey();
value = String.valueOf( entry.getValue());
if(key.equals("month")||key.equals("�")) {
continue ;
}else if(value.equals("�")) {
value="0";
} line_chart_dataset.addValue( Double.valueOf(value.toString()) ,key,map.get("month").toString());
}
// System.out.println( Double.valueOf(map.get("体育部").toString()));
// line_chart_dataset.addValue( Double.valueOf(map.get("体育部").toString()) ,"体育部",map.get("month").toString());
// line_chart_dataset.addValue( Double.valueOf(map.get("体育部").toString()) ,"体育部",map.get("month").toString());
// line_chart_dataset.addValue( Double.valueOf(map.get("学校办公室").toString()) ,"学校办公室",map.get("month").toString());
// line_chart_dataset.addValue( Double.valueOf(map.get("数学科学学院").toString()),"数学科学学院",map.get("month").toString());
// line_chart_dataset.addValue( Double.valueOf(map.get("校团委(创新创业学院)").toString()),"校团委(创新创业学院)" ,map.get("month").toString());
// line_chart_dataset.addValue( Double.valueOf(map.get("经济与管理学院").toString()) ,"经济与管理学院",map.get("month").toString());
}
JFreeChart lineChartObject = ChartFactory.createLineChart(
"支付失败率排行榜","",
"占比",
line_chart_dataset,PlotOrientation.VERTICAL,
true,true,false);
CategoryPlot plot = (CategoryPlot) lineChartObject.getPlot();
plot.setBackgroundPaint(Color.WHITE);
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
Font kfont = new Font("宋体", Font.PLAIN, 18);
lineChartObject.getLegend().setItemFont(kfont);
plot.getDomainAxis().setLabelFont(kfont);
plot.getRangeAxis().setLabelFont(kfont);
lineChartObject.getTitle().setFont(kfont);
int width = 500;
int height = 400; // LineAndShapeRenderer renderer = (LineAndShapeRenderer)plot.getRenderer();
// DecimalFormat decimalformat1 = new DecimalFormat("##.##");//数据点显示数据值的格式
// renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", decimalformat1));
// renderer.setItemLabelsVisible(true);//设置项标签显示
// renderer.setBaseItemLabelsVisible(true);//基本项标签显示
// renderer.setShapesFilled(Boolean.TRUE);//在数据点显示实心的小图标
// renderer.setShapesVisible(true);//设置显示小图标
try {
ChartUtilities.saveChartAsJPEG(new File(picturePath+"imgB_4.png") ,lineChartObject, width ,height);
} catch (IOException e) {
e.printStackTrace(); }
}
public void createImgB5(String mouth) {
//传入月份即可
Map<String, Object> map = new HashMap<String, Object>();
map.put("month", mouth);
List<Map<String, Object>> payFailCountPre5 = olpayInfoService.getPayFailCountPre5(map); DefaultCategoryDataset ds2= new DefaultCategoryDataset();
for(int i=0; i<payFailCountPre5.size(); i++) {
Map<String, Object> map1 = payFailCountPre5.get(i);
ds2.addValue( Double.valueOf(map1.get("NUMS").toString()) , "数据" ,map1.get("CHARGE_SNAME").toString());
}
DefaultCategoryDataset capDataset2 = ds2;
String filePath2 = JfreeChartUtils.newInstance()
.setTiltle("支付失败数量排行榜(个人)")
.setLabel("占比", "")
.addAnnotation(annotation)
.setSize(JfreeChartUtils.large_width, JfreeChartUtils.large_heigh)
.generateBarChart(capDataset2, picturePath, "imgB_5");
}
public void createImgC2(String mouth) {
//传入月份即可
Map<String, Object> map = new HashMap<String, Object>();
map.put("month", mouth);
List<Map<String, Object>> avgInputTimePre3 = sPzinfoService.getAvgInputTimePre3(map); DefaultCategoryDataset ds2= new DefaultCategoryDataset();
for(int i=0; i<avgInputTimePre3.size(); i++) {
Map<String, Object> map1 = avgInputTimePre3.get(i);
ds2.addValue( Double.valueOf(map1.get("HOURS").toString()) , "数据" ,map1.get("INPUT_NAME").toString());
if(i==0) {
params.put("e10", map1.get("INPUT_NAME").toString());
params.put("e11", map1.get("HOURS").toString());
}
}
DefaultCategoryDataset capDataset2 = ds2;
String filePath2 = JfreeChartUtils.newInstance()
.setTiltle("平均制单时长排行榜(h)")
.setLabel("占比", "")
.addAnnotation(annotation)
.setSize(JfreeChartUtils.large_width, JfreeChartUtils.large_heigh)
.generateBarChart2(capDataset2, picturePath, "imgC_2");
}
public void createImgC3(String mouth) throws ParseException {
// //修改impl 传入时间生成 日历
List<Map<String, Object>> list = sPzinfoService.getAvgInputTimeByMonth(mouth);
DefaultCategoryDataset line_chart_dataset = new DefaultCategoryDataset();
for(int i=0;i<list.size();i++) {
Map<String, Object>map=list.get(i);
line_chart_dataset.addValue( Double.valueOf(map.get("avgInputTime").toString()) ,"数据",map.get("month").toString());
}
JFreeChart lineChartObject = ChartFactory.createLineChart(
"平均制单月度统计","",
"占比",
line_chart_dataset,PlotOrientation.VERTICAL,
true,true,false);
CategoryPlot plot = (CategoryPlot) lineChartObject.getPlot();
plot.setBackgroundPaint(Color.WHITE);
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
Font kfont = new Font("宋体", Font.PLAIN, 18);
lineChartObject.getLegend().setItemFont(kfont);
plot.getDomainAxis().setLabelFont(kfont);
plot.getRangeAxis().setLabelFont(kfont);
lineChartObject.getTitle().setFont(kfont);
int width = 500;
int height = 400; LineAndShapeRenderer renderer = (LineAndShapeRenderer)plot.getRenderer();
DecimalFormat decimalformat1 = new DecimalFormat("##.##");//数据点显示数据值的格式
renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", decimalformat1));
renderer.setItemLabelsVisible(true);//设置项标签显示
renderer.setBaseItemLabelsVisible(true);//基本项标签显示
renderer.setShapesFilled(Boolean.TRUE);//在数据点显示实心的小图标
renderer.setShapesVisible(true);//设置显示小图标
try {
ChartUtilities.saveChartAsJPEG(new File(picturePath+"imgC_3.png") ,lineChartObject, width ,height);
} catch (IOException e) {
e.printStackTrace();
}
}
public void createImgD1(String mouth) {
//不变
List<Map<String, String>> creditGradeStatistic = sPersonCreditService.getCreditGradeStatistic();
DefaultCategoryDataset ds2= new DefaultCategoryDataset();
for(int i=0; i<creditGradeStatistic.size(); i++) {
Map<String, String> map1 = creditGradeStatistic.get(i);
ds2.addValue( Double.valueOf(map1.get("人数").toString()) , "数据" ,map1.get("信用等级").toString());
}
DefaultCategoryDataset capDataset2 = ds2;
String filePath2 = JfreeChartUtils.newInstance()
.setTiltle("全国信用等级统计")
.setLabel("占比", "")
.addAnnotation(annotation)
.setSize(JfreeChartUtils.large_width, JfreeChartUtils.large_heigh)
.generateBarChart2(capDataset2, picturePath, "imgD_1");
}
public void createImgD2(String mouth) {
//不变
Map<String, String> paramMap =new HashMap<>();
paramMap.put("type", "desc");
List<SPersonCreditModel> highAndLowPre5 = sPersonCreditService.getHighAndLowPre5(paramMap); DefaultCategoryDataset ds2= new DefaultCategoryDataset();
for(int i=0; i<highAndLowPre5.size(); i++) {
ds2.addValue( Double.valueOf(highAndLowPre5.get(i).getCreditScore()) , "数据" ,highAndLowPre5.get(i).getUserName().toString());
}
DefaultCategoryDataset capDataset2 = ds2;
String filePath2 = JfreeChartUtils.newInstance()
.setTiltle("高分排名前五")
.setLabel("占比", "")
.addAnnotation(annotation)
.setSize(JfreeChartUtils.large_width, JfreeChartUtils.large_heigh)
.generateBarChart2(capDataset2, picturePath, "imgD_2"); Map<String, String> paramMap2asc =new HashMap<>();
paramMap2asc.put("type", "asc");
List<SPersonCreditModel> highAndLowPre5asc = sPersonCreditService.getHighAndLowPre5(paramMap2asc); DefaultCategoryDataset ds= new DefaultCategoryDataset();
for(int i=0; i<highAndLowPre5asc.size(); i++) {
ds.addValue( Double.valueOf(highAndLowPre5asc.get(i).getCreditScore()) , "数据" ,highAndLowPre5asc.get(i).getUserName().toString());
}
DefaultCategoryDataset capDataset = ds;
String filePath = JfreeChartUtils.newInstance()
.setTiltle("低分排名前五")
.setLabel("占比", "")
.addAnnotation(annotation)
.setSize(JfreeChartUtils.large_width, JfreeChartUtils.large_heigh)
.generateBarChart2(capDataset, picturePath, "imgD_3"); }
}
package com.gwt.utils; import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.io.File;
import java.util.Date; import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.annotations.CategoryTextAnnotation;
import org.jfree.chart.annotations.XYTextAnnotation;
import org.jfree.chart.axis.AxisLabelLocation;
import org.jfree.chart.axis.CategoryAnchor;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.PieLabelLinkStyle;
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.StandardBarPainter;
import org.jfree.chart.renderer.xy.StandardXYBarPainter;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RectangleInsets;
import org.jfree.ui.TextAnchor;
import org.jfree.util.StringUtils;
import org.springframework.beans.factory.annotation.Value; public class JfreeChartUtils { public static int small_width = 400;
public static int small_heigh = 310; public static int middle_width = 410;
public static int middle_heigh = 390; //public static int large_width = 360;
public static int large_width = 770;
public static int large_heigh = 270; private int def_width = middle_width;
private int def_heigh = middle_heigh;
private String yLabel;
private String xLabel;
private String title;
private String annotation;
//Font font = new Font("宋体", Font.PLAIN, 18);
private static Font FONT = new Font("宋体", Font.PLAIN, 14);
private static Font annotationFont = new Font("宋体", Font.PLAIN, 10);
public static Color[] CHART_COLORS = { new Color(31, 129, 188), new Color(92, 92, 97), new Color(144, 237, 125),
new Color(255, 188, 117), new Color(153, 158, 255), new Color(255, 117, 153), new Color(253, 236, 109),
new Color(128, 133, 232), new Color(158, 90, 102), new Color(255, 204, 102) };// 妫版粏澹� static {
setChartTheme();
} private JfreeChartUtils() {
} public static JfreeChartUtils newInstance() {
return new JfreeChartUtils();
} /**
* 娑擃厽鏋冩稉濠氼暯閺嶅嘲绱� 鐟欙絽鍠呮稊杈╃垳
*/
public static void setChartTheme() {
// 鐠佸墽鐤嗘稉顓熸瀮娑撳顣介弽宄扮础 鐟欙絽鍠呮稊杈╃垳
StandardChartTheme chartTheme = new StandardChartTheme("CN");
// 鐠佸墽鐤嗛弽鍥暯鐎涙ぞ缍�
chartTheme.setExtraLargeFont(FONT);
// 鐠佸墽鐤嗛崶鍙ョ伐閻ㄥ嫬鐡ф担锟�
chartTheme.setRegularFont(FONT);
// 鐠佸墽鐤嗘潪鏉戞倻閻ㄥ嫬鐡ф担锟�
chartTheme.setLargeFont(FONT);
chartTheme.setSmallFont(FONT);
chartTheme.setTitlePaint(new Color(10, 10, 10));
chartTheme.setSubtitlePaint(new Color(10, 10, 10));
chartTheme.setAxisLabelPaint(new Color(10, 10, 10));// 閸ф劖鐖f潪瀛樼垼妫版ɑ鏋冪�涙顤侀懝锟�
chartTheme.setTickLabelPaint(new Color(10, 10, 10));// 閸掕瀹抽弫鏉跨摟 chartTheme.setLegendBackgroundPaint(Color.WHITE);// 鐠佸墽鐤嗛弽鍥ㄦ暈
chartTheme.setLegendItemPaint(Color.BLACK);//
chartTheme.setChartBackgroundPaint(Color.WHITE);
// 缂佹ê鍩楁0婊嗗缂佹ê鍩楁0婊嗗.鏉烆喖绮ㄦ笟娑樼安閸燂拷
// paintSequence,outlinePaintSequence,strokeSequence,outlineStrokeSequence,shapeSequence Paint[] OUTLINE_PAINT_SEQUENCE = new Paint[] { Color.WHITE };
// 缂佹ê鍩楅崳銊╊杹閼瑰弶绨�
DefaultDrawingSupplier drawingSupplier = new DefaultDrawingSupplier(CHART_COLORS, CHART_COLORS,
OUTLINE_PAINT_SEQUENCE, DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
chartTheme.setDrawingSupplier(drawingSupplier); chartTheme.setPlotBackgroundPaint(Color.WHITE);// 缂佹ê鍩楅崠鍝勭厵
chartTheme.setPlotOutlinePaint(Color.BLACK);// 缂佹ê鍩楅崠鍝勭厵婢舵牞绔熷锟�
chartTheme.setLabelLinkPaint(new Color(8, 55, 114));// 闁剧偓甯撮弽鍥╊劮妫版粏澹�
chartTheme.setLabelLinkStyle(PieLabelLinkStyle.CUBIC_CURVE); chartTheme.setAxisOffset(new RectangleInsets(0, 0, 0, 0));
chartTheme.setDomainGridlinePaint(new Color(192, 208, 224));// X閸ф劖鐖f潪鏉戠�惄瀵哥秹閺嶅ジ顤侀懝锟�
chartTheme.setRangeGridlinePaint(new Color(192, 192, 192));// Y閸ф劖鐖f潪瀛樻寜楠炲磭缍夐弽濂割杹閼癸拷 chartTheme.setBaselinePaint(Color.WHITE);
chartTheme.setCrosshairPaint(Color.BLUE);// 娑撳秶鈥樼�规艾鎯堟稊锟�
chartTheme.setBarPainter(new StandardBarPainter());// 鐠佸墽鐤嗛弻杈╁Ц閸ョ偓瑕嗛弻锟�
chartTheme.setXYBarPainter(new StandardXYBarPainter());// XYBar 濞撳弶鐓� chartTheme.setItemLabelPaint(Color.black);
chartTheme.setThermometerPaint(Color.white);// 濞撯晛瀹崇拋锟� ChartFactory.setChartTheme(chartTheme);
} public String generateTimeSeriesChart(TimeSeriesCollection dataset, String srcPath, Paint itemLabelPaint, String fileName) {
// if (StringUtils.isEmpty(srcPath)) {
// return null;
// }
try {
JFreeChart chart = ChartFactory.createTimeSeriesChart(title, xLabel, yLabel, dataset, false, true, false);
// chart.setTextAntiAlias(false);
XYPlot xyPlot = (XYPlot) chart.getPlot();
xyPlot.setRangeGridlinesVisible(false);// 娑撳秵妯夌粈铏圭帛閸ユ儳灏崺鐔虹秹閺嶏拷
xyPlot.setDomainGridlinesVisible(false); // 閼惧嘲褰囬弰鍓с仛缁炬寧娼惃鍕嚠鐠烇拷
XYLineAndShapeRenderer xyShape = (XYLineAndShapeRenderer) xyPlot.getRenderer(); // xyShape.setDefaultStroke(new BasicStroke(0.5f)); // 鐠佸墽鐤嗙痪鍨啍
xyShape.setSeriesPaint(0, new Color(10, 100, 200));// 鐠佸墽鐤嗙痪璺ㄦ畱妫版粏澹� // 鐠佸墽鐤嗛幏鎰仯
xyShape.setSeriesPaint(1, new Color(0, 0, 0, 0));
xyShape.setSeriesShapesVisible(1, true); xyShape.setSeriesFillPaint(1, Color.RED);// 鐠佸墽鐤嗛幏鎰仯妫版粏澹�
xyShape.setUseFillPaint(true);// 鐠佸墽鐤唂alse閹锋劗鍋f0婊嗗鐠佸墽鐤嗘稉宥囨晸閺侊拷
xyShape.setSeriesShape(1, new java.awt.geom.Ellipse2D.Double(-2.5D, -2.5D, 5D, 5D));// 鐠佸墽鐤嗛幏鎰仯婢堆冪毈 // 鐠佸墽鐤嗛弰鍓с仛閸婏拷
xyShape.setSeriesItemLabelsVisible(1, true);
xyShape.setSeriesItemLabelGenerator(1, new StandardXYItemLabelGenerator());
xyShape.setSeriesItemLabelFont(1, annotationFont);
xyShape.setSeriesItemLabelPaint(1, itemLabelPaint); xyShape.setSeriesPositiveItemLabelPosition(1,
new ItemLabelPosition(ItemLabelAnchor.INSIDE1, TextAnchor.TOP_LEFT)); // y 鏉烇拷
NumberAxis numberaxis = (NumberAxis) xyPlot.getRangeAxis();
// numberaxis.setRange(42, 58);
// numberaxis.setTickUnit(new NumberTickUnit(2)); // 闂傛挳娈ф稉锟�2
numberaxis.setLowerMargin(0.12);
numberaxis.setUpperMargin(0.06); // x 鏉烇拷
DateAxis dateAxis = (DateAxis) xyPlot.getDomainAxis();
dateAxis.setLabelLocation(AxisLabelLocation.HIGH_END);
dateAxis.setLowerMargin(0.06);
dateAxis.setUpperMargin(0.15);
/*
* SimpleDateFormat frm = new SimpleDateFormat("HH:mm"); int count =
* 30;//闂傛挳娈ф稉锟�30閸掑棝鎸� dateAxis.setTickUnit(new
* DateTickUnit(DateTickUnitType.MINUTE,count,frm));
*/ // 濞h濮為弬鍥ㄦ拱閸栫儤鏁為柌锟�
if (annotation != null) {
annotation = " " + annotation;
XYTextAnnotation text = new XYTextAnnotation(annotation, dateAxis.getRange().getLowerBound(), // X 閸ф劖鐖�
numberaxis.getRange().getLowerBound()); // Y 閸ф劖鐖�
text.setFont(annotationFont);
text.setTextAnchor(TextAnchor.BOTTOM_LEFT);
xyPlot.addAnnotation(text);
}
// if (StringUtils.isEmpty(fileName)) {
// fileName = new Date().getTime() + "XY";
// }
String filePath = srcPath + File.separator + fileName + ".png";
ChartUtilities.saveChartAsPNG(new File(filePath), chart, def_width, def_heigh);
return filePath;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} public String generateBarChart(DefaultCategoryDataset dataset, String srcPath, String fileName) {
// if (StringUtils.isEmpty(srcPath)) {
// return null;
// }
try {
JFreeChart chart = ChartFactory.createBarChart(title, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, // 閸ユ崘銆冮弬鐟版倻
false, // 閺勵垰鎯侀弰鍓с仛閸ュ彞绶�
true, // 閺勵垰鎯侀悽鐔稿灇閹绘劗銇氬銉ュ徔
false);
// chart.setTextAntiAlias(false);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.setRangeGridlinesVisible(false);// 娑撳秵妯夌粈铏圭帛閸ユ儳灏崺鐔虹秹閺嶏拷
plot.setDomainGridlinesVisible(false); // 閼惧嘲褰囬弰鍓с仛缁炬寧娼惃鍕嚠鐠烇拷
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setSeriesPaint(0, Color.GREEN);// 鐠佸墽鐤嗘0婊嗗 renderer.setMaximumBarWidth(0.1); // y 鏉烇拷
NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();
// numberaxis.setRange(42, 58);
// numberaxis.setTickUnit(new NumberTickUnit(2)); // 闂傛挳娈ф稉锟�2
numberaxis.setUpperMargin(0.06); // x 鏉烇拷
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLowerMargin(0.01);
domainAxis.setUpperMargin(0.01);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45); // 濞h濮為弬鍥ㄦ拱閸栫儤鏁為柌锟�
if (annotation != null) {
CategoryTextAnnotation text = new CategoryTextAnnotation(annotation,
dataset.getColumnKeys().get(0).toString(), // X 閸ф劖鐖�
numberaxis.getRange().getUpperBound()); // Y 閸ф劖鐖�
text.setFont(annotationFont);
text.setTextAnchor(TextAnchor.TOP_LEFT);
text.setCategoryAnchor(CategoryAnchor.START);
plot.addAnnotation(text);
} // if (StringUtils.isEmpty(fileName)) {
// fileName = new Date().getTime() + "Bar";
// }
String filePath = srcPath + File.separator + fileName + ".png";
ChartUtilities.saveChartAsPNG(new File(filePath), chart, def_width, def_heigh);
return filePath;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//横向
public String generateBarChart2(DefaultCategoryDataset dataset, String srcPath, String fileName) {
// if (StringUtils.isEmpty(srcPath)) {
// return null;
// }
try {
JFreeChart chart = ChartFactory.createBarChart(title, xLabel, yLabel, dataset, PlotOrientation.HORIZONTAL, // 閸ユ崘銆冮弬鐟版倻
false, // 閺勵垰鎯侀弰鍓с仛閸ュ彞绶�
true, // 閺勵垰鎯侀悽鐔稿灇閹绘劗銇氬銉ュ徔
false);
// chart.setTextAntiAlias(false);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.setRangeGridlinesVisible(false);// 娑撳秵妯夌粈铏圭帛閸ユ儳灏崺鐔虹秹閺嶏拷
plot.setDomainGridlinesVisible(false); // 閼惧嘲褰囬弰鍓с仛缁炬寧娼惃鍕嚠鐠烇拷
BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setSeriesPaint(0, Color.GREEN);// 鐠佸墽鐤嗘0婊嗗 renderer.setMaximumBarWidth(0.1); // y 鏉烇拷
NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();
// numberaxis.setRange(42, 58);
// numberaxis.setTickUnit(new NumberTickUnit(2)); // 闂傛挳娈ф稉锟�2
numberaxis.setUpperMargin(0.06); // x 鏉烇拷
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLowerMargin(0.01);
domainAxis.setUpperMargin(0.01);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45); // 濞h濮為弬鍥ㄦ拱閸栫儤鏁為柌锟�
if (annotation != null) {
CategoryTextAnnotation text = new CategoryTextAnnotation(annotation,
dataset.getColumnKeys().get(0).toString(), // X 閸ф劖鐖�
numberaxis.getRange().getUpperBound()); // Y 閸ф劖鐖�
text.setFont(annotationFont);
text.setTextAnchor(TextAnchor.TOP_LEFT);
text.setCategoryAnchor(CategoryAnchor.START);
plot.addAnnotation(text);
} // if (StringUtils.isEmpty(fileName)) {
// fileName = new Date().getTime() + "Bar";
// }
String filePath = srcPath + File.separator + fileName + ".png";
ChartUtilities.saveChartAsPNG(new File(filePath), chart, def_width, def_heigh);
return filePath;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} public JfreeChartUtils setSize(int width, int heigh) {
this.def_width = width < 0 ? middle_width : width;
this.def_heigh = heigh < 0 ? middle_heigh : heigh;
return this;
} public JfreeChartUtils setLabel(String yLabel, String xLabel) {
this.yLabel = yLabel;
this.xLabel = xLabel;
return this;
} public JfreeChartUtils setTiltle(String title) {
this.title = title;
return this;
} public JfreeChartUtils addAnnotation(String annotation) {
this.annotation = annotation;
return this;
} }
操作word的更多相关文章
- python操作word入门
1.安装pywin32 http://sourceforge.net/projects/pywin32 在files里去找适合你的python版本.截止此文,最新版本是pywin32-219快捷路径: ...
- C#中操作Word(1)—— word对象模型介绍
一.开发环境布置 C#中添加对Word的支持,只需添加对Microsoft.Office.Interop.Word的命名空间,如下图所示,右键点击“引用”,在弹出的“添加引用”对话框中选中COM标签页 ...
- C#操作Word的超详细总结
本文中用C#来操作Word,包括: 创建Word: 插入文字,选择文字,编辑文字的字号.粗细.颜色.下划线等: 设置段落的首行缩进.行距: 设置页面页边距和纸张大小: 设置页眉.页码: 插入图片,设置 ...
- C#操作word模板插入文字、图片及表格详细步骤
c#操作word模板插入文字.图片及表格 1.建立word模板文件 person.dot用书签 标示相关字段的填充位置 2.建立web应用程序 加入Microsoft.Office.Interop.W ...
- C#操作Word的辅助类(word2003) 修改完善版
转自:http://blog.csdn.net/jiutao_tang/article/details/6567608 该类在他人编写的几个类基础上扩展完善而来,主要功能有: (1)插入文本 (2)插 ...
- 黄聪:C#操作Word表格的常见操作(转)
几种常见C#操作Word表格操作有哪些呢?让我们来看看具体的实例演示: bool saveChange = false; //C#操作Word表格操作 object missing = System. ...
- c#操作word表格
http://www.webshu.net/jiaocheng/programme/ASPNET/200804/6499.html <% if request("infoid" ...
- Aspose.Words操作word生成PDF文档
Aspose.Words操作word生成PDF文档 using Aspose.Words; using System; using System.Collections.Generic; using ...
- OpenXML操作word
OpenXML概述 项目中经常需要操作word,之前的方式是采用COM接口,这个接口很不稳定,经常报错.现在开始采用OpenXML.OpenXML(OOXML)是微软在Office 2007中提出的一 ...
- c# 操作word
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
随机推荐
- VAR模型学习笔记
目录 1 定义 VAR模型的具体步骤 建模步骤及公式 代码实现 1 定义 VAR模型除了分析自身滞后项的影响外,还分析其他相关因素的滞后项对未来值产生的影响参考 用来分析随机扰动对系统的动态冲击的大小 ...
- 记录 shell学习过程(6)while 以及 while的嵌套 以及 until
while中的5种条件 1.数学比较 read -p "Num :" num1 ] do echo 'greater' sleep done 2.字符串比较 read -p &qu ...
- 《TCP/IP入门经典》摘录--Part 3
TCP/IP协议系统 3.子网划分和CIDR 子网 划分网络 为什么需要划分子网? 子网划分就是在网络 ID 之下提供了第 2 层逻辑组织.路由器能够把数据报发送给网络里的某个子网地址(一般对应于一个 ...
- ORA_12514:TNS:listener does not currently know of service requested in connect descriptor
问题描述 ORA_12514:TNS:listener does not currently know of service requested in connect descriptor 解决方式 ...
- C short类型的内存分析
#include<stdio.h> #include<limits.h> void main(){ //printf("short%d, int%d, long%d ...
- JS高级---bind方法
bind方法 复制了一份的时候, 把参数传入到了f1函数中, x===>10, y===>20, null就是this, 默认就是window bind方法是复制的意思, 参数可以在复制的 ...
- git免密拉取代码
里介绍通过ssh公钥的方式免密拉取代码 以linux服务器为例,windows方式是一样的 1.用命令生成ssh key ssh-keygen -t rsa -C "xx@xxxcom&qu ...
- Having用法以及其和Where区别
例如,进行分组语句: select year,count(id) num from tblPlantProduce group by year 在这条语句中若要筛选出年份>2005年的有两种方式 ...
- object转为string
object为null时 错误:object.tostring() 空指针 正确:(string)object
- 1.4 面试问题整理: ATM机取款
流程图: