Java Code Examples for org.apache.poi.xwpf.usermodel.XWPFParagraph#createRun()

The following examples show how to use org.apache.poi.xwpf.usermodel.XWPFParagraph#createRun() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TocTest.java    From poi-tl with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) throws FileNotFoundException, IOException {
    XWPFDocument doc = new XWPFDocument(new FileInputStream("toc.docx"));

    XWPFStyles styles = doc.getStyles();
    System.out.println(styles);

    XWPFParagraph p = doc.createParagraph();
    XWPFRun run = p.createRun();
    run.setText("Heading 1");
    p.getCTP().addNewPPr();
    p.getCTP().getPPr().addNewPStyle();
    p.setStyle(HEADING1);

    XWPFParagraph tocPara = doc.createParagraph();
    CTP ctP = tocPara.getCTP();
    CTSimpleField toc = ctP.addNewFldSimple();
    toc.setInstr("TOC \\h");
    toc.setDirty(STOnOff.TRUE);

    System.out.println(doc.isEnforcedUpdateFields());

    // doc.enforceUpdateFields();

    // doc.createTOC();

    doc.write(new FileOutputStream("CreateWordBookmark.docx"));
    doc.close();
}
 
Example 2
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Inserts a run in the generated document. The new run is a copy from the specified run.
 * 
 * @param paragraph
 *            the {@link XWPFParagraph} to modify
 * @param srcRun
 *            the run to copy
 * @return the inserted {@link XWPFRun}
 */
private XWPFRun insertRun(XWPFParagraph paragraph, XWPFRun srcRun) {

    final XWPFParagraph newParagraph;
    if (srcRun.getParent() != currentTemplateParagraph || forceNewParagraph) {
        newParagraph = createNewParagraph(generatedDocument, (XWPFParagraph) srcRun.getParent());
        forceNewParagraph = false;
    } else {
        newParagraph = paragraph;
    }

    XWPFRun newRun = null;
    if (srcRun instanceof XWPFHyperlinkRun) {
        // Hyperlinks meta information is saved in the paragraph and not in the run. So we have to update the paragrapah with a copy of
        // the hyperlink to insert.
        CTHyperlink newHyperlink = newParagraph.getCTP().addNewHyperlink();
        newHyperlink.set(((XWPFHyperlinkRun) srcRun).getCTHyperlink());

        newRun = new XWPFHyperlinkRun(newHyperlink, srcRun.getCTR(), srcRun.getParent());
        newParagraph.addRun(newRun);
    } else {
        newRun = newParagraph.createRun();
        newRun.getCTR().set(srcRun.getCTR());
    }
    return newRun;
}
 
Example 3
Source File: PDF2WordExample.java    From tutorials with MIT License 6 votes vote down vote up
private static void generateDocFromPDF(String filename) throws IOException {
	XWPFDocument doc = new XWPFDocument();

	String pdf = filename;
	PdfReader reader = new PdfReader(pdf);
	PdfReaderContentParser parser = new PdfReaderContentParser(reader);

	for (int i = 1; i <= reader.getNumberOfPages(); i++) {
		TextExtractionStrategy strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
		String text = strategy.getResultantText();
		XWPFParagraph p = doc.createParagraph();
		XWPFRun run = p.createRun();
		run.setText(text);
		run.addBreak(BreakType.PAGE);
	}
	FileOutputStream out = new FileOutputStream("src/output/pdf.docx");
	doc.write(out);
	out.close();
	reader.close();
	doc.close();
}
 
Example 4
Source File: ETLWordDocumentGenerator.java    From WhiteRabbit with Apache License 2.0 6 votes vote down vote up
private static void addTableLevelSection(CustomXWPFDocument document, ETL etl) throws InvalidFormatException, FileNotFoundException {
	XWPFParagraph tmpParagraph = document.createParagraph();
	XWPFRun tmpRun = tmpParagraph.createRun();
	
	MappingPanel mappingPanel = new MappingPanel(etl.getTableToTableMapping());
	mappingPanel.setShowOnlyConnectedItems(true);
	int height = mappingPanel.getMinimumSize().height;
	mappingPanel.setSize(800, height);
	
	tmpRun.setText(mappingPanel.getSourceDbName() + " Data Mapping Approach to " + mappingPanel.getTargetDbName());
	tmpRun.setFontSize(18);
	
	BufferedImage im = new BufferedImage(800, height, BufferedImage.TYPE_INT_ARGB);
	im.getGraphics().setColor(Color.WHITE);
	im.getGraphics().fillRect(0, 0, im.getWidth(), im.getHeight());
	mappingPanel.paint(im.getGraphics());
	document.addPicture(im, 600, height * 6 / 8);
}
 
Example 5
Source File: Issue149.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
@Test
public void testNewMergeNew3() throws Exception {
    source = new NiceXWPFDocument();

    target = new NiceXWPFDocument();
    XWPFParagraph createParagraph = target.createParagraph();
    createParagraph.createRun();

    result = source.merge(target);

    assertEquals(result.getParagraphs().size(), 1);
    assertEquals(result.getParagraphArray(0).getText(), "");

    source.close();
    target.close();
    result.close();

}
 
Example 6
Source File: Issue149.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
@Test
public void testNewMergeOld2() throws Exception {
    source = new NiceXWPFDocument();
    XWPFParagraph createParagraph = source.createParagraph();
    createParagraph.createRun();

    target = new NiceXWPFDocument(new FileInputStream(resource));
    result = source.merge(target);

    XWPFParagraph paragraph = result.getParagraphArray(0);
    assertEquals(paragraph.getText(), "");
    paragraph = result.getParagraphArray(1);
    assertEquals(paragraph.getText(), "{{title}}");
    paragraph = result.getParagraphArray(2);
    assertEquals(paragraph.getText(), "{{+students}}");
    paragraph = result.getParagraphArray(3);
    assertEquals(paragraph.getText(), "{{+teachers}}");

    source.close();
    target.close();
    result.close();

}
 
Example 7
Source File: M2DocUtils.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets or create the first {@link XWPFRun} of the given {@link XWPFDocument}.
 * 
 * @param document
 *            the {@link XWPFDocument}
 * @return the first {@link XWPFRun} of the given {@link XWPFDocument} or the created one if none existed
 */
public static XWPFRun getOrCreateFirstRun(XWPFDocument document) {
    final XWPFRun res;

    final XWPFParagraph paragraph;
    if (!document.getParagraphs().isEmpty()) {
        paragraph = document.getParagraphs().get(0);
    } else {
        paragraph = document.createParagraph();
    }
    if (!paragraph.getRuns().isEmpty()) {
        res = paragraph.getRuns().get(0);
    } else {
        res = paragraph.createRun();
    }

    return res;
}
 
Example 8
Source File: BookmarkManager.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Inserts a pending reference to the given name in the given {@link XWPFParagraph}.
 * 
 * @param paragraph
 *            the {@link XWPFParagraph}
 * @param name
 *            the bookmark name
 * @param text
 *            the text
 */
public void insertReference(XWPFParagraph paragraph, String name, String text) {
    final CTBookmark bookmark = bookmarks.get(name);
    if (bookmark != null) {
        insertReference(paragraph, bookmark, text);
    } else {
        final XWPFRun messageRun = paragraph.createRun();
        final CTText ref = insertPendingReference(paragraph, name, text);
        ref.setStringValue(String.format(REF_TAG, name));
        messagePositions.put(ref, messageRun);
        Set<CTText> pendingRefs = pendingReferences.get(name);
        if (pendingRefs == null) {
            pendingRefs = new LinkedHashSet<>();
            pendingReferences.put(name, pendingRefs);
        }
        pendingRefs.add(ref);
        xmlObjectToName.put(ref, name);
    }
}
 
Example 9
Source File: NumbericRenderPolicy.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
private static XWPFRun createRunLine(XWPFRun run, BodyContainer bodyContainer, Style style,
        BigInteger numID) {
    XWPFParagraph paragraph = bodyContainer.insertNewParagraph(run);
    StyleUtils.styleParagraph(paragraph, style);
    paragraph.setNumID(numID);
    return paragraph.createRun();
}
 
Example 10
Source File: BookmarkManager.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Inserts a reference to the given {@link CTBookmark} with the given text in the given {@link XWPFParagraph}.
 * 
 * @param paragraph
 *            the {@link XWPFParagraph}
 * @param name
 *            the bookmark name
 * @param text
 *            the text
 * @return the {@link CTText} corresponding to the reference.
 */
private CTText insertPendingReference(XWPFParagraph paragraph, String name, String text) {
    final byte[] id = getReferenceID(name);
    final XWPFRun beginRun = paragraph.createRun();
    beginRun.getCTR().setRsidR(id);
    beginRun.getCTR().addNewFldChar().setFldCharType(STFldCharType.BEGIN);

    final XWPFRun preservedRun = paragraph.createRun();
    preservedRun.getCTR().setRsidR(id);
    final CTText pgcttext = preservedRun.getCTR().addNewInstrText();
    pgcttext.setSpace(Space.PRESERVE);

    final XWPFRun separateRun = paragraph.createRun();
    separateRun.getCTR().setRsidR(id);
    separateRun.getCTR().addNewFldChar().setFldCharType(STFldCharType.SEPARATE);

    final XWPFRun textRun = paragraph.createRun();
    textRun.getCTR().setRsidR(id);
    textRun.getCTR().addNewRPr().addNewNoProof();
    textRun.setText(text);
    textRun.setBold(true);

    final XWPFRun endRun = paragraph.createRun();
    endRun.getCTR().setRsidR(id);
    endRun.getCTR().addNewFldChar().setFldCharType(STFldCharType.END);

    return pgcttext;
}
 
Example 11
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create a new run in the cell's paragraph and set this run's text, and apply the given style to the cell and its paragraph.
 * 
 * @param cell
 *            Cell to fill in
 * @param mCell
 *            the cell to read data from
 */
private void setCellContent(XWPFTableCell cell, MCell mCell) {
    XWPFParagraph cellParagraph = cell.getParagraphs().get(0);
    XWPFRun cellRun = cellParagraph.createRun();
    if (mCell != null) {
        final MElement contents = mCell.getContents();
        if (mCell.getVAlignment() != null) {
            cell.setVerticalAlignment(getVAglignment(mCell.getVAlignment()));
        }
        if (contents != null) {
            final IBody savedGeneratedDocument = generatedDocument;
            final XWPFParagraph savedGeneratedParagraph = currentGeneratedParagraph;
            final XWPFParagraph savedTemplateParagraph = currentTemplateParagraph;
            generatedDocument = cell;
            currentGeneratedParagraph = cellParagraph;
            currentTemplateParagraph = cellParagraph;
            try {
                insertObject(cellParagraph, contents, cellRun);
            } finally {
                generatedDocument = savedGeneratedDocument;
                currentGeneratedParagraph = savedGeneratedParagraph;
                currentTemplateParagraph = savedTemplateParagraph;
            }
            cellParagraph.removeRun(cellParagraph.getRuns().indexOf(cellRun));
        }
        final Color backGroundColor = mCell.getBackgroundColor();
        if (backGroundColor != null) {
            cell.setColor(hexColor(backGroundColor));
        }
    }
}
 
Example 12
Source File: SimpleTable.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
public static void createSimpleTable() throws Exception {
    @SuppressWarnings("resource")
XWPFDocument doc = new XWPFDocument();

    XWPFTable table = doc.createTable(3, 3);

    table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE");

    // table cells have a list of paragraphs; there is an initial
    // paragraph created when the cell is created. If you create a
    // paragraph in the document to put in the cell, it will also
    // appear in the document following the table, which is probably
    // not the desired result.
    XWPFParagraph p1 = table.getRow(0).getCell(0).getParagraphs().get(0);

    XWPFRun r1 = p1.createRun();
    r1.setBold(true);
    r1.setText("The quick brown fox");
    r1.setItalic(true);
    r1.setFontFamily("Courier");
    r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
    r1.setTextPosition(100);

    table.getRow(2).getCell(2).setText("only text");

    FileOutputStream out = new FileOutputStream("simpleTable.docx");
    doc.write(out);
    out.close();
}
 
Example 13
Source File: ETLWordDocumentGenerator.java    From WhiteRabbit with Apache License 2.0 5 votes vote down vote up
private static void addSourceTablesAppendix(CustomXWPFDocument document, ETL etl) {
	XWPFParagraph paragraph = document.createParagraph();
	XWPFRun run = paragraph.createRun();
	run.addBreak(BreakType.PAGE);
	run.setText("Appendix: source tables");
	run.setFontSize(18);
	
	for (Table sourceTable : etl.getSourceDatabase().getTables()) {
		paragraph = document.createParagraph();
		run = paragraph.createRun();
		run.setText("Table: " + sourceTable.getName());
		run.setFontSize(14);
		
		createDocumentParagraph(document, sourceTable.getComment());
		
		XWPFTable table = document.createTable(sourceTable.getFields().size() + 1, 4);
		// table.setWidth(2000);
		XWPFTableRow header = table.getRow(0);
		setTextAndHeaderShading(header.getCell(0), "Field");
		setTextAndHeaderShading(header.getCell(1), "Type");
		setTextAndHeaderShading(header.getCell(2), "Most freq. value");
		setTextAndHeaderShading(header.getCell(3), "Comment");
		int rowNr = 1;
		for (Field sourceField : sourceTable.getFields()) {
			XWPFTableRow row = table.getRow(rowNr++);
			row.getCell(0).setText(sourceField.getName());
			row.getCell(1).setText(sourceField.getType());
			row.getCell(2).setText(sourceField.getValueCounts().getMostFrequentValue());
			createCellParagraph(row.getCell(3), sourceField.getComment().trim());
		}
		
	}
	
	run.setFontSize(18);
}
 
Example 14
Source File: RawCopier.java    From M2Doc with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Copies the given {@link IBody} to the given {@link XWPFParagraph}.
 * 
 * @param outputParagraph
 *            the output {@link XWPFParagraph}
 * @param body
 *            the {@link IBody}
 * @param bookmarkManager
 *            the {@link BookmarkManager} to update or <code>null</code>
 * @return the new current {@link XWPFParagraph}
 * @throws Exception
 *             if something goes wrong
 */
public XWPFParagraph copyBody(XWPFParagraph outputParagraph, IBody body, BookmarkManager bookmarkManager)
        throws Exception {
    XWPFParagraph res = null;

    if (body.getBodyElements().isEmpty()) {
        res = outputParagraph;
    } else {
        final IBody outputBody = outputParagraph.getBody();
        boolean inline;
        if (!(outputBody instanceof XWPFTableCell) && outputParagraph.getRuns().size() == 1
            && outputParagraph.getRuns().get(0).getText(0).length() == 0) {
            removeParagraph(outputBody, outputParagraph);
            inline = false;
        } else {
            inline = true;
        }

        final Map<String, String> inputRelationIdToOutputMap = new HashMap<>();
        final Map<URI, URI> inputPartURIToOutputPartURI = new HashMap<>();
        for (IBodyElement element : body.getBodyElements()) {
            if (element instanceof XWPFParagraph) {
                final XWPFParagraph inputParagraph = (XWPFParagraph) element;
                if (inline) {
                    // inline the all paragraph
                    copyParagraphFragment(inputRelationIdToOutputMap, inputPartURIToOutputPartURI, outputParagraph,
                            inputParagraph, null, null);
                    res = outputParagraph;
                } else {
                    res = copyParagraph(outputBody, inputRelationIdToOutputMap, inputPartURIToOutputPartURI,
                            inputParagraph, bookmarkManager);
                }
            } else if (element instanceof XWPFTable) {
                final XWPFTable inputTable = (XWPFTable) element;
                copyTable(outputBody, inputRelationIdToOutputMap, inputPartURIToOutputPartURI, inputTable,
                        bookmarkManager);
                res = null;
            } else if (element instanceof XWPFSDT) {
                copyCTSdtBlock(outputBody, AbstractBodyParser.getCTSdtBlock(outputBody, (XWPFSDT) element));
                res = null;
            } else {
                throw new IllegalStateException("unknown body element.");
            }
            inline = false;
        }

        if (res != null && outputBody instanceof XWPFTableCell && res.getRuns().isEmpty()) {
            res.createRun();
        }
    }

    return res;
}
 
Example 15
Source File: ETLWordDocumentGenerator.java    From WhiteRabbit with Apache License 2.0 4 votes vote down vote up
private static void addTargetTableSection(CustomXWPFDocument document, ETL etl, Table targetTable) throws InvalidFormatException, FileNotFoundException {
	XWPFParagraph paragraph = document.createParagraph();
	XWPFRun run = paragraph.createRun();
	run.addBreak(BreakType.PAGE);
	
	run.setText("Table name: " + targetTable.getName());
	run.setFontSize(18);
	
	createDocumentParagraph(document, targetTable.getComment());
	
	for (ItemToItemMap tableToTableMap : etl.getTableToTableMapping().getSourceToTargetMaps())
		if (tableToTableMap.getTargetItem() == targetTable) {
			Table sourceTable = (Table) tableToTableMap.getSourceItem();
			Mapping<Field> fieldtoFieldMapping = etl.getFieldToFieldMapping(sourceTable, targetTable);
			
			paragraph = document.createParagraph();
			run = paragraph.createRun();
			run.setText("Reading from " + tableToTableMap.getSourceItem());
			run.setFontSize(14);
			
			createDocumentParagraph(document, tableToTableMap.getLogic());
			
			createDocumentParagraph(document, tableToTableMap.getComment());
			
			// Add picture of field to field mapping
			MappingPanel mappingPanel = new MappingPanel(fieldtoFieldMapping);
			mappingPanel.setShowOnlyConnectedItems(true);
			int height = mappingPanel.getMinimumSize().height;
			mappingPanel.setSize(800, height);
			
			BufferedImage im = new BufferedImage(800, height, BufferedImage.TYPE_INT_ARGB);
			im.getGraphics().setColor(Color.WHITE);
			im.getGraphics().fillRect(0, 0, im.getWidth(), im.getHeight());
			mappingPanel.paint(im.getGraphics());
			document.addPicture(im, 600, height * 6 / 8);
			
			// Add table of field to field mapping
			XWPFTable table = document.createTable(fieldtoFieldMapping.getTargetItems().size() + 1, 4);
			// table.setWidth(2000);
			XWPFTableRow header = table.getRow(0);
			setTextAndHeaderShading(header.getCell(0), "Destination Field");
			setTextAndHeaderShading(header.getCell(1), "Source Field");
			setTextAndHeaderShading(header.getCell(2), "Logic");
			setTextAndHeaderShading(header.getCell(3), "Comment");
			int rowNr = 1;
			for (MappableItem targetField : fieldtoFieldMapping.getTargetItems()) {
				XWPFTableRow row = table.getRow(rowNr++);
				row.getCell(0).setText(targetField.getName());
				
				StringBuilder source = new StringBuilder();
				StringBuilder logic = new StringBuilder();
				StringBuilder comment = new StringBuilder();
				for (ItemToItemMap fieldToFieldMap : fieldtoFieldMapping.getSourceToTargetMaps()) {
					if (fieldToFieldMap.getTargetItem() == targetField) {
						if (source.length() != 0)
							source.append("\n");
						source.append(fieldToFieldMap.getSourceItem().getName().trim());
						
						if (logic.length() != 0)
							logic.append("\n");
						logic.append(fieldToFieldMap.getLogic().trim());
						
						if (comment.length() != 0)
							comment.append("\n");
						comment.append(fieldToFieldMap.getComment().trim());
					}
				}
				
				for (Field field : targetTable.getFields()) {
					if (field.getName().equals(targetField.getName())) {
						if (comment.length() != 0)
							comment.append("\n");
						comment.append(field.getComment().trim());
					}
				}
				
				createCellParagraph(row.getCell(1), source.toString());
				createCellParagraph(row.getCell(2), logic.toString());
				createCellParagraph(row.getCell(3), comment.toString());
			}
		}
	
}
 
Example 16
Source File: ETLWordDocumentGenerator.java    From WhiteRabbit with Apache License 2.0 4 votes vote down vote up
private static void addToParagraph(XWPFParagraph paragraph, String text) {
	XWPFRun run = paragraph.createRun();
	run.setText(text);
}
 
Example 17
Source File: WordExport.java    From frpMgr with MIT License 4 votes vote down vote up
public void fillTableAtBookMark(String bookMarkName, List<Map<String, String>> content) {

		//rowNum来比较标签在表格的哪一行
		int rowNum = 0;

		//首先得到标签
		BookMark bookMark = bookMarks.getBookmark(bookMarkName);
		Map<String, String> columnMap = new HashMap<String, String>();
		Map<String, Node> styleNode = new HashMap<String, Node>();

		//标签是否处于表格内
		if (bookMark.isInTable()) {

			//获得标签对应的Table对象和Row对象
			XWPFTable table = bookMark.getContainerTable();
			XWPFTableRow row = bookMark.getContainerTableRow();
//			CTRow ctRow = row.getCtRow();
			List<XWPFTableCell> rowCell = row.getTableCells();
			for (int i = 0; i < rowCell.size(); i++) {
				columnMap.put(i + "", rowCell.get(i).getText().trim());
				//System.out.println(rowCell.get(i).getParagraphs().get(0).createRun().getFontSize());
				//System.out.println(rowCell.get(i).getParagraphs().get(0).getCTP());
				//System.out.println(rowCell.get(i).getParagraphs().get(0).getStyle());

				//获取该单元格段落的xml,得到根节点
				Node node1 = rowCell.get(i).getParagraphs().get(0).getCTP().getDomNode();

				//遍历根节点的所有子节点
				for (int x = 0; x < node1.getChildNodes().getLength(); x++) {
					if (node1.getChildNodes().item(x).getNodeName().equals(BookMark.RUN_NODE_NAME)) {
						Node node2 = node1.getChildNodes().item(x);

						//遍历所有节点为"w:r"的所有自己点,找到节点名为"w:rPr"的节点
						for (int y = 0; y < node2.getChildNodes().getLength(); y++) {
							if (node2.getChildNodes().item(y).getNodeName().endsWith(BookMark.STYLE_NODE_NAME)) {

								//将节点为"w:rPr"的节点(字体格式)存到HashMap中
								styleNode.put(i + "", node2.getChildNodes().item(y));
							}
						}
					} else {
						continue;
					}
				}
			}

			//循环对比,找到该行所处的位置,删除改行			
			for (int i = 0; i < table.getNumberOfRows(); i++) {
				if (table.getRow(i).equals(row)) {
					rowNum = i;
					break;
				}
			}
			table.removeRow(rowNum);

			for (int i = 0; i < content.size(); i++) {
				//创建新的一行,单元格数是表的第一行的单元格数,
				//后面添加数据时,要判断单元格数是否一致
				XWPFTableRow tableRow = table.createRow();
				CTTrPr trPr = tableRow.getCtRow().addNewTrPr();
				CTHeight ht = trPr.addNewTrHeight();
				ht.setVal(BigInteger.valueOf(360));
			}

			//得到表格行数
			int rcount = table.getNumberOfRows();
			for (int i = rowNum; i < rcount; i++) {
				XWPFTableRow newRow = table.getRow(i);

				//判断newRow的单元格数是不是该书签所在行的单元格数
				if (newRow.getTableCells().size() != rowCell.size()) {

					//计算newRow和书签所在行单元格数差的绝对值
					//如果newRow的单元格数多于书签所在行的单元格数,不能通过此方法来处理,可以通过表格中文本的替换来完成
					//如果newRow的单元格数少于书签所在行的单元格数,要将少的单元格补上
					int sub = Math.abs(newRow.getTableCells().size() - rowCell.size());
					//将缺少的单元格补上
					for (int j = 0; j < sub; j++) {
						newRow.addNewTableCell();
					}
				}

				List<XWPFTableCell> cells = newRow.getTableCells();

				for (int j = 0; j < cells.size(); j++) {
					XWPFParagraph para = cells.get(j).getParagraphs().get(0);
					XWPFRun run = para.createRun();
					if (content.get(i - rowNum).get(columnMap.get(j + "")) != null) {

						//改变单元格的值,标题栏不用改变单元格的值 
						run.setText(content.get(i - rowNum).get(columnMap.get(j + "")) + "");

						//将单元格段落的字体格式设为原来单元格的字体格式
						run.getCTR().getDomNode().insertBefore(styleNode.get(j + "").cloneNode(true), run.getCTR().getDomNode().getFirstChild());
					}

					para.setAlignment(ParagraphAlignment.CENTER);
				}
			}
		}
	}
 
Example 18
Source File: M2DocUtils.java    From M2Doc with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Appends the given error message at the end of the given {@link XWPFParagraph}.
 * 
 * @param paragraph
 *            the {@link XWPFParagraph}
 * @param level
 *            the {@link ValidationMessageLevel}
 * @param message
 *            the message
 * @return the created {@link TemplateValidationMessage}
 */
public static TemplateValidationMessage appendMessageRun(XWPFParagraph paragraph, ValidationMessageLevel level,
        String message) {
    final XWPFRun run = paragraph.createRun();

    setRunMessage(run, level, message);

    return new TemplateValidationMessage(level, message, run);
}
 
Example 19
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Inserts a {@link XWPFRun} run containing the given text to the given {@link XWPFParagraph}.
 * 
 * @param paragraph
 *            the {@link XWPFParagraph} to modify
 * @param srcRun
 *            the {@link XWPFRun} to copy the style from
 * @param fragment
 *            the text fragment to insert
 * @return the inserted {@link XWPFRun}
 */
private XWPFRun insertFragment(XWPFParagraph paragraph, XWPFRun srcRun, String fragment) {
    XWPFRun generatedRun = paragraph.createRun();
    generatedRun.getCTR().set(srcRun.getCTR().copy());
    generatedRun.getCTR().getInstrTextList().clear();
    generatedRun.setText(fragment);
    return generatedRun;
}