com.qihang.winter.poi.word.parse.ParseWord07.java Source code

Java tutorial

Introduction

Here is the source code for com.qihang.winter.poi.word.parse.ParseWord07.java

Source

/**
 * Copyright 2013-2015 JueYue (qrb.jueyue@gmail.com)
 *   
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qihang.winter.poi.word.parse;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFFooter;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
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 com.qihang.winter.poi.cache.WordCache;
import com.qihang.winter.poi.util.PoiPublicUtil;
import com.qihang.winter.poi.word.entity.MyXWPFDocument;
import com.qihang.winter.poi.word.entity.WordImageEntity;
import com.qihang.winter.poi.word.entity.params.ExcelListEntity;
import com.qihang.winter.poi.word.parse.excel.ExcelEntityParse;
import com.qihang.winter.poi.word.parse.excel.ExcelMapParse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ?07Word,?,?,?
 * 
 * @author Zerrion
 * @date 2013-11-16
 * @version 1.0
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class ParseWord07 {

    private static final Logger LOGGER = LoggerFactory.getLogger(ParseWord07.class);

    /**
     * 
     * 
     * @author Zerrion
     * @date 2013-11-20
     * @param obj
     * @param currentRun
     * @throws Exception
     */
    private void addAnImage(WordImageEntity obj, XWPFRun currentRun) throws Exception {
        Object[] isAndType = PoiPublicUtil.getIsAndType(obj);
        String picId;
        try {
            picId = currentRun.getParagraph().getDocument().addPictureData((byte[]) isAndType[0],
                    (Integer) isAndType[1]);
            ((MyXWPFDocument) currentRun.getParagraph().getDocument()).createPicture(currentRun, picId,
                    currentRun.getParagraph().getDocument().getNextPicNameNumber((Integer) isAndType[1]),
                    obj.getWidth(), obj.getHeight());

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

    }

    /**
     * ???
     * 
     * @param map
     * @author Zerrion
     * @date 2013-11-16
     */
    private void changeValues(XWPFParagraph paragraph, XWPFRun currentRun, String currentText,
            List<Integer> runIndex, Map<String, Object> map) throws Exception {
        Object obj = PoiPublicUtil.getRealValue(currentText, map);
        if (obj instanceof WordImageEntity) {// 
            currentRun.setText("", 0);
            addAnImage((WordImageEntity) obj, currentRun);
        } else {
            currentText = obj.toString();
            currentRun.setText(currentText, 0);
        }
        for (int k = 0; k < runIndex.size(); k++) {
            paragraph.getRuns().get(runIndex.get(k)).setText("", 0);
        }
        runIndex.clear();
    }

    /**
     * ?
     * 
     * @author Zerrion
     * @date 2013-11-18
     * @return
     * @throws Exception
     */
    private Object checkThisTableIsNeedIterator(XWPFTableCell cell, Map<String, Object> map) throws Exception {
        String text = cell.getText().trim();
        // ?
        if (text.startsWith("{{") && text.endsWith("}}") && text.indexOf("in ") != -1) {
            return PoiPublicUtil.getRealValue(text.replace("in ", "").trim(), map);
        }
        return null;
    }

    /**
     * ?
     * 
     * @author Zerrion
     * @date 2013-11-17
     * @param paragraphs
     * @param map
     */
    private void parseAllParagraphic(List<XWPFParagraph> paragraphs, Map<String, Object> map) throws Exception {
        XWPFParagraph paragraph;
        for (int i = 0; i < paragraphs.size(); i++) {
            paragraph = paragraphs.get(i);
            if (paragraph.getText().indexOf("{{") != -1) {
                parseThisParagraph(paragraph, map);
            }

        }

    }

    /**
     * ??
     * 
     * @author Zerrion
     * @date 2013-11-16
     * @param paragraph
     * @param map
     */
    private void parseThisParagraph(XWPFParagraph paragraph, Map<String, Object> map) throws Exception {
        XWPFRun run;
        XWPFRun currentRun = null;// run,?set,???
        String currentText = "";// ?text
        String text;
        Boolean isfinde = false;// ???{{
        List<Integer> runIndex = new ArrayList<Integer>();// ?run,
        for (int i = 0; i < paragraph.getRuns().size(); i++) {
            run = paragraph.getRuns().get(i);
            text = run.getText(0);
            if (StringUtils.isEmpty(text)) {
                continue;
            } // ""?
            if (isfinde) {
                currentText += text;
                if (currentText.indexOf("{{") == -1) {
                    isfinde = false;
                    runIndex.clear();
                } else {
                    runIndex.add(i);
                }
                if (currentText.indexOf("}}") != -1) {
                    changeValues(paragraph, currentRun, currentText, runIndex, map);
                    currentText = "";
                    isfinde = false;
                }
            } else if (text.indexOf("{") >= 0) {// ?
                currentText = text;
                isfinde = true;
                currentRun = run;
            } else {
                currentText = "";
            }
            if (currentText.indexOf("}}") != -1) {
                changeValues(paragraph, currentRun, currentText, runIndex, map);
                isfinde = false;
            }
        }

    }

    private void parseThisRow(List<XWPFTableCell> cells, Map<String, Object> map) throws Exception {
        for (XWPFTableCell cell : cells) {
            parseAllParagraphic(cell.getParagraphs(), map);
        }
    }

    /**
     * ?
     * 
     * @author Zerrion
     * @date 2013-11-17
     * @param table
     * @param map
     */
    private void parseThisTable(XWPFTable table, Map<String, Object> map) throws Exception {
        XWPFTableRow row;
        List<XWPFTableCell> cells;
        Object listobj;
        ExcelEntityParse excelEntityParse = new ExcelEntityParse();
        for (int i = 0; i < table.getNumberOfRows(); i++) {
            row = table.getRow(i);
            cells = row.getTableCells();
            if (cells.size() == 1) {
                listobj = checkThisTableIsNeedIterator(cells.get(0), map);
                if (listobj == null) {
                    parseThisRow(cells, map);
                } else if (listobj instanceof ExcelListEntity) {
                    table.removeRow(i);// 
                    excelEntityParse.parseNextRowAndAddRow(table, i, (ExcelListEntity) listobj);
                } else {
                    table.removeRow(i);// 
                    ExcelMapParse.parseNextRowAndAddRow(table, i, (List) listobj);
                }
            } else {
                parseThisRow(cells, map);
            }
        }
    }

    /**
     * ?07Word
     * 
     * @author Zerrion
     * @date 2013-11-16
     * @return
     * @throws Exception
     */
    public XWPFDocument parseWord(String url, Map<String, Object> map) throws Exception {
        MyXWPFDocument doc = WordCache.getXWPFDocumen(url);
        parseWordSetValue(doc, map);
        return doc;
    }

    /**
     * ?07Word
     * 
     * @author Zerrion
     * @date 2013-11-16
     * @return
     * @throws Exception
     */
    public void parseWord(XWPFDocument document, Map<String, Object> map) throws Exception {
        parseWordSetValue((MyXWPFDocument) document, map);
    }

    private void parseWordSetValue(MyXWPFDocument doc, Map<String, Object> map) throws Exception {
        // ?
        parseAllParagraphic(doc.getParagraphs(), map);
        // ?,
        parseHeaderAndFoot(doc, map);
        // ?
        XWPFTable table;
        Iterator<XWPFTable> itTable = doc.getTablesIterator();
        while (itTable.hasNext()) {
            table = itTable.next();
            if (table.getText().indexOf("{{") != -1) {
                parseThisTable(table, map);
            }
        }

    }

    /**
     * ?
     * @param doc
     * @param map
     * @throws Exception
     */
    private void parseHeaderAndFoot(MyXWPFDocument doc, Map<String, Object> map) throws Exception {
        List<XWPFHeader> headerList = doc.getHeaderList();
        for (XWPFHeader xwpfHeader : headerList) {
            for (int i = 0; i < xwpfHeader.getListParagraph().size(); i++) {
                parseThisParagraph(xwpfHeader.getListParagraph().get(i), map);
            }
        }
        List<XWPFFooter> footerList = doc.getFooterList();
        for (XWPFFooter xwpfFooter : footerList) {
            for (int i = 0; i < xwpfFooter.getListParagraph().size(); i++) {
                parseThisParagraph(xwpfFooter.getListParagraph().get(i), map);
            }
        }

    }
}