package com.njcn.csharmonic.utils.eventReport;

import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.util.Calendar;

public class WordUtils {


    public static void main(String[] args)throws Exception {

        // 空白文档
        XWPFDocument document= new XWPFDocument();
        //把文档写进本地系统
        FileOutputStream out = new FileOutputStream(new File("create_table.docx"));
        //设定标题格式
        setHeadingStyle(document);
        //添加标题
        XWPFParagraph titleParagraph = document.createParagraph();
        setParagraphStyle(titleParagraph);
        addLine(titleParagraph,11);
        //设置段落居中
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleParagraphRun = titleParagraph.createRun();
        addParagraph(titleParagraphRun,"宋体",15,"000000","四川省供电公司",true);

        addLine(titleParagraph,3);
        XWPFRun titleParagraphBigRun = titleParagraph.createRun();
        addParagraph(titleParagraphBigRun,"宋体",36,"000000","电压暂降事件分析报告",true);
        addLine(titleParagraph,19);

        XWPFRun titleParagraphDateRun = titleParagraph.createRun();
        addParagraph(titleParagraphDateRun,"宋体",14,"000000","日期： 2018年1月3号",true);
        titleParagraph.setPageBreak(true);


        //段落
        XWPFParagraph statisticsParagraph = document.createParagraph();
        setParagraphStyle(statisticsParagraph);
        //段前分页
        statisticsParagraph.setPageBreak(true);
        statisticsParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun statisticsRun = statisticsParagraph.createRun();
        addParagraph(statisticsRun,"宋体",24,"000000","电压暂降事件分析报告",false);



        XWPFParagraph introductionParagraph= document.createParagraph();
        setParagraphStyle(introductionParagraph);
        introductionParagraph.setStyle("标题 1");
        introductionParagraph.setAlignment(ParagraphAlignment.LEFT);
        XWPFRun introductionRun = introductionParagraph.createRun();
        addParagraph(introductionRun,"宋体",15,"000000","1. 引言",true);

        XWPFParagraph introductionContentParagraph = document.createParagraph();
        //  首行缩进---段落
        setParagraphStyle(introductionContentParagraph);
        introductionContentParagraph.setAlignment(ParagraphAlignment.LEFT);
        introductionContentParagraph.setIndentationFirstLine(200);
        XWPFRun introductionContentRun=introductionContentParagraph.createRun();
        addParagraph(introductionContentRun,"宋体",11,"000000","对所选中区间内电压暂降事件进行分析，能够直观清晰查看相应的暂降事件信息。",false);

        XWPFParagraph objectParagraph=document.createParagraph();
        setParagraphStyle(objectParagraph);
        objectParagraph.setStyle("标题 1");
        objectParagraph.setAlignment(ParagraphAlignment.LEFT);
        XWPFRun  objectRun= objectParagraph.createRun();
        addParagraph(objectRun,"宋体",15,"000000","2. 报告分析对象:",true);

        XWPFParagraph  objectContentParagraph = document.createParagraph();
        setParagraphStyle(objectContentParagraph);
        objectContentParagraph.setAlignment(ParagraphAlignment.LEFT);
        objectContentParagraph.setIndentationFirstLine(200);
        XWPFRun objectContentRun = objectContentParagraph.createRun();
        addParagraph(objectContentRun,"宋体",11,"000000","成都供电公司—>锦江区变电站—>锦江2号。",false);

        XWPFParagraph   timeParagraph = document.createParagraph();
        timeParagraph.setStyle("标题 1");
        timeParagraph.setAlignment(ParagraphAlignment.LEFT);
        setParagraphStyle(timeParagraph);
        XWPFRun  timeRun = timeParagraph.createRun();
        addParagraph(timeRun,"宋体",15,"000000","3. 报告分析时间:",true);

        XWPFParagraph timeContentParagraph = document.createParagraph();
        setParagraphStyle(timeContentParagraph);
        timeContentParagraph.setAlignment(ParagraphAlignment.LEFT);
        timeContentParagraph.setIndentationFirstLine(200);
        XWPFRun timeContentRun = timeContentParagraph.createRun();
        addParagraph(timeContentRun,"宋体",11,"000000","2017年12月21日至2017年12月30日。",false);


        XWPFParagraph   summaeParagraph =  document.createParagraph();
        setParagraphStyle(summaeParagraph);
        summaeParagraph.setStyle("标题 1");
        summaeParagraph.setAlignment(ParagraphAlignment.LEFT);
        XWPFRun summaeRun = summaeParagraph.createRun();
        addParagraph(summaeRun,"宋体",15,"000000","4. 汇总信息:",true);


        XWPFParagraph   summaeTableParagraph =  document.createParagraph();
        setParagraphStyle(summaeTableParagraph);
        summaeTableParagraph.setStyle("标题 2");
        summaeTableParagraph.setAlignment(ParagraphAlignment.LEFT);
        summaeTableParagraph.setIndentationFirstLine(200);
        XWPFRun summaeTableRun = summaeTableParagraph.createRun();
        addParagraph(summaeTableRun,"宋体",11,"000000","4.1 表格",false);


        //工作经历表格
        XWPFTable summaTable = document.createTable();

        //列宽自动分割
        CTTblWidth summaTableWidth = summaTable.getCTTbl().addNewTblPr().addNewTblW();
        summaTableWidth.setType(STTblWidth.DXA);
        summaTableWidth.setW(BigInteger.valueOf(9072));

        //表格第一行
        XWPFTableRow summaTableRowOne = summaTable.getRow(0);
        XWPFParagraph excelParagraph= document.createParagraph();
        setParagraphStyle(excelParagraph);
        excelParagraph.setAlignment(ParagraphAlignment.CENTER);
        excelParagraph.setVerticalAlignment(TextAlignment.CENTER);
        setExcelHeadContent(excelParagraph,summaTableRowOne,"序号","暂降发生时刻","暂降幅值(%)","持续时间(ms)","暂降类型","暂降原因","严重度");

        //表格第二行
        XWPFTableRow summaTableRowTwo = summaTable.createRow();
        setExcelContent(excelParagraph,summaTableRowTwo,"1","2017-11-24 14:26:56.490","9","20","未识别","未明","0.91");

        //表格第三行
        XWPFTableRow summaTableRowThree = summaTable.createRow();
        setExcelContent(excelParagraph,summaTableRowThree,"2","2017-11-24 14:25:46.472","15","19","未识别","未明","0.85");

        XWPFParagraph   summaePicParagraph =  document.createParagraph();
        summaePicParagraph.setStyle("标题 2");
        summaePicParagraph.setAlignment(ParagraphAlignment.LEFT);
        summaePicParagraph.setIndentationFirstLine(200);
        XWPFRun summaePicRun = summaePicParagraph.createRun();
        addParagraph(summaePicRun,"宋体",11,"000000","4.2 ITIC曲线",false);


        CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
        XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);

        //添加页眉
        CTP ctpHeader = CTP.Factory.newInstance();
        CTR ctrHeader = ctpHeader.addNewR();
        CTText ctHeader = ctrHeader.addNewT();
        String headerText = "Java POI create MS word file.";
        ctHeader.setStringValue(headerText);
        XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, document);
        //设置为右对齐
        headerParagraph.setAlignment(ParagraphAlignment.RIGHT);
        XWPFParagraph[] parsHeader = new XWPFParagraph[1];
        parsHeader[0] = headerParagraph;
        policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, parsHeader);


        //添加页脚
        CTP ctpFooter = CTP.Factory.newInstance();
        CTR ctrFooter = ctpFooter.addNewR();
        CTText ctFooter = ctrFooter.addNewT();
        String footerText = "http://blog.csdn.net/zhouseawater";
        ctFooter.setStringValue(footerText);
        XWPFParagraph footerParagraph = new XWPFParagraph(ctpFooter, document);
        headerParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFParagraph[] parsFooter = new XWPFParagraph[1];
        parsFooter[0] = footerParagraph;
        policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);

        document.write(out);
        out.close();

    }

    public static void  setParagraphStyle(XWPFParagraph paragraph){
            paragraph.setSpacingBefore(100);
            paragraph.setSpacingAfter(100);
    }

    /**
     * 返回指定格式的段落 居中型
     * @param document 文档对象
     */
    public static XWPFParagraph  getCenterParagraph(XWPFDocument document){
    	XWPFParagraph paragraph = document.createParagraph();
    	setParagraphStyle(paragraph);
    	paragraph.setAlignment(ParagraphAlignment.CENTER);
    	paragraph.setVerticalAlignment(TextAlignment.CENTER);
    	return paragraph;
    }

    /**
     * 返回指定格式的段落 居左型
     * @param document 文档对象
     */
    public static XWPFParagraph  getLeftParagraph(XWPFDocument document){
    	XWPFParagraph paragraph = document.createParagraph();
    	setParagraphStyle(paragraph);
    	paragraph.setAlignment(ParagraphAlignment.LEFT);
    	return paragraph;
    }



    /**
     * 添加换行符
     * @param paragraph 指定段落
     * @param amount    行数
     * */
    public static void  addLine(XWPFParagraph paragraph,Integer  amount){
            XWPFRun run = paragraph.createRun();
            run.setFontSize(11);
            for(int i=0;i<amount;i++){
                run.addCarriageReturn();
            }
    }


    /**
     * 添加段落文本
     * @param run 文本执行对象
     * @param fontFamily  字体类型
     * @param fontSize     字体大小
     * @param backgroundColor  字体颜色
     * @param bold  是否加粗
     */
    public static void  addParagraph(XWPFRun run,String fontFamily,Integer fontSize,String backgroundColor,String message,boolean bold){
            run.setText(message);
            run.setColor(backgroundColor);
            run.setFontSize(fontSize);
            run.setFontFamily(fontFamily);
            run.setBold(bold);
    }


    /**
     * 增加自定义标题样式。这里用的是stackoverflow的源码
     *
     * @param docxDocument 目标文档
     * @param strStyleId 样式名称
     * @param headingLevel 样式级别
     */
    public static void addCustomHeadingStyle(XWPFDocument docxDocument, String strStyleId, int headingLevel) {

        CTStyle ctStyle = CTStyle.Factory.newInstance();
        ctStyle.setStyleId(strStyleId);

        CTString styleName = CTString.Factory.newInstance();
        styleName.setVal(strStyleId);
        ctStyle.setName(styleName);

        CTDecimalNumber indentNumber = CTDecimalNumber.Factory.newInstance();
        indentNumber.setVal(BigInteger.valueOf(headingLevel));

        // lower number > style is more prominent in the formats bar
        ctStyle.setUiPriority(indentNumber);

        CTOnOff onoffnull = CTOnOff.Factory.newInstance();
        ctStyle.setUnhideWhenUsed(onoffnull);

        // style shows up in the formats bar
        ctStyle.setQFormat(onoffnull);

        // style defines a heading of the given level
        CTPPr ppr = CTPPr.Factory.newInstance();
        ppr.setOutlineLvl(indentNumber);
        ctStyle.setPPr(ppr);

        XWPFStyle style = new XWPFStyle(ctStyle);

        // is a null op if already defined
        XWPFStyles styles = docxDocument.createStyles();

        style.setType(STStyleType.PARAGRAPH);
        styles.addStyle(style);

    }

    /**
     * 设置文档中标题格式
     * */
    public static void setHeadingStyle(XWPFDocument document){
        addCustomHeadingStyle(document, "标题 1", 1);
        addCustomHeadingStyle(document, "标题 2", 2);
        addCustomHeadingStyle(document, "标题 3", 3);
        addCustomHeadingStyle(document, "标题 4", 4);
        addCustomHeadingStyle(document, "标题 5", 5);
        addCustomHeadingStyle(document, "标题 6", 6);
        addCustomHeadingStyle(document, "标题 7", 7);
    }

    /**
     * 给表格添加一行数据
     * @param paragraph 段落对象
     * @param row 行对象
     * @param data 不定长度的数据
     */
    public static void  setExcelContent(XWPFParagraph paragraph, XWPFTableRow  row,String...  data){
                for (int i=0;i<data.length;i++){
                    XWPFRun run =paragraph.createRun();
                    run.setFontFamily("宋体");
                    run.setText(data[i]);
                    row.getCell(i).setParagraph(paragraph);
                    paragraph.removeRun(0);
                }
    }



    /**
     * 添加表头标题一行数据
     * @param paragraph 段落对象
     * @param row 行对象
     * @param data 不定长度的数据
     */
    public static void  setExcelHeadContent(XWPFParagraph paragraph, XWPFTableRow  row,String...  data){
                XWPFRun run= paragraph.createRun();
                run.setFontFamily("宋体");
                run.setBold(true);
                run.setText(data[0]);
                row.getCell(0).setParagraph(paragraph);
                paragraph.removeRun(0);
                for(int i=1;i<data.length;i++){
                    XWPFRun run1 =paragraph.createRun();
                    run1.setFontFamily("宋体");
                    run1.setBold(true);
                    run1.setText(data[i]);
                    row.addNewTableCell().setParagraph(paragraph);
                    paragraph.removeRun(0);
                }
    }

    /**
     * 获取当前的日期
     * @return
     */
    public static String getRightNow(){
        Calendar rightNow    =    Calendar.getInstance();
        Integer year = rightNow.get(Calendar.YEAR);
        Integer month = rightNow.get(Calendar.MONTH)+1;
        Integer day = rightNow.get(rightNow.DAY_OF_MONTH);
        return year+"年"+month+"月"+day+"日";
    }

}
