首先生成word文档时候需要准备spire.doc-3.8.1.jar包以及poi-ooxml-3.15.jar包

/**
	 * 加载模版文件
	 * @param templateFilePath
	 * @return
	 */
	public Document loadTemplateDocument(String templateFilePath) throws FileNotFoundException {
		Document document = new Document();
		//这里是复制word文档,可以省去很多功夫
		document.loadFromFile(templateFilePath);
		return document;
	}
public void createDocumentStyleLast(int countA,, Document doc) {
		Section section = doc.getSections().get(0);
		Table table =section.getTables().get(0);
		if (countA== 0) {
			return;
		}
		for (int i = 0 ; i < countA- 1; i++){
		//复制模板中的第三行单元格
			TableRow row = table.getRows().get(3).deepClone();
			table.getRows().insert(4 + i ,row);
		}
	}

设置表格标题内容

private void fillTitle(Table table) {
	//这里第一个循环是循环行的,第二个循环是循环单元格
		for(int i = 0; i < table.getRows().getCount(); i++) {
			for (int j = 0; j < table.getRows().get(i).getCells().getCount(); j++) {
				TableCell cell = table.getRows().get(i).getCells().get(j);
				cell.getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
				Paragraph p = cell.getParagraphs().get(0);
				if (i == 0 && j == 0 ) {
				//添加内容
					TextRange range1 = p.appendText( "A");
					range1.getCharacterFormat().setFontName("宋体");
					range1.getCharacterFormat().setBold(true);
				} else if (i == 1 && j== 1) {
					
					TextRange range1 = p.appendText("");
					range1.getCharacterFormat().setFontName("宋体");
					range1.getCharacterFormat().setFontSize(12f);
					p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
					p.setText("B");
				} else if (i == 1 && j== 3) {
					TextRange range1 = p.appendText("");
					range1.getCharacterFormat().setFontName("宋体");
					range1.getCharacterFormat().setFontSize(12f);
					p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
					p.setText("test");
				} else if (i == 1 && j== 5) {
					TextRange range1 = p.appendText("");
					range1.getCharacterFormat().setFontName("宋体");
					range1.getCharacterFormat().setFontSize(12f);
					p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
					p.setText(startDate + "-" + endDate);
				}
			}
		}
	}

//插入图片的方法

private void fillLogo(String image, Paragraph paragraph) {
		paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);
		if (StringUtils.isBlank(image)) {
			paragraph.appendText(getBlankStr(165));
			return;
		}
		HttpURLConnection conn = null;
		InputStream inputStream = null;
		BufferedImage image = null;
		try {
			URL url = new URL(image);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(20 * 1000);
			ByteArrayOutputStream output = new ByteArrayOutputStream();

			inputStream = conn.getInputStream();
			IOUtils.copy(inputStream, output);

			ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(output.toByteArray());
			ByteArrayInputStream imageStream = new ByteArrayInputStream(output.toByteArray());
			DocPicture picture = paragraph.appendPicture(byteArrayInputStream);

			image = ImageIO.read(imageStream);
			float initWith = 0;
			float initHigh = 0;
			initHigh = 20f;
			float highScaler = initHigh/(float) image.getHeight();
			initWith = (float)image.getWidth() * highScaler;
			picture.setWidth(initWith);
			picture.setHeight(initHigh);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			inputStream.close();
		}

	}

//设置表格内容

	for(int i = 0; i < table.getRows().getCount(); i++) {
			for (int j = 0; j < table.getRows().get(i).getCells().getCount(); j++) {
				TableCell cell = table.getRows().get(i).getCells().get(j);
				cell.getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
				Paragraph p = cell.getParagraphs().get(0);
		if (j == 0 ) {
					p.setText(A);
				} else if (j== 1) {
					p.setText(B);
				} else if (j== 2) {
					p.setText(C);
				} else if (j== 3) {
					p.setText(D);
				} else if (j== 4) {
					p.setText(E);
				} else if (j== 5) {
					p.setText(F);
				} else if (j== 6) {
					p.setText(G);
				} else if (j== 7) {
					p.setText(H);
				}
			}
		}

//word文档添加水印

private void addWaterMarker(String waterMarkText, String waterMarkPicture, Document document) {
		// 图片水印
		// 加载图片
		// 设置图片环绕方式
		DocPicture picture = new DocPicture(document);
		picture.loadImage(waterMarkPicture);
		picture.setRotation(320);
		picture.setTextWrappingStyle(TextWrappingStyle.Behind);

		// 文字水印
		// 添加艺术字并设置大小
		ShapeObject shape = new ShapeObject(document, ShapeType.Text_Plain_Text);
		if (waterMarkText.length() > 12) {
			waterMarkText = waterMarkText.substring(0, 12) + "...";
			shape.setWidth(20 * waterMarkText.length());
		} else {
			shape.setWidth(20 * waterMarkText.length());
		}
		shape.setHeight(20);
		//设置艺术字文本内容、位置及样式
		shape.setVerticalPosition(1);
		shape.setHorizontalPosition(1);
		shape.setRotation(320);
		shape.getWordArt().setFontFamily("宋体");
		shape.getWordArt().setText(waterMarkText);
		shape.setFillColor(new Color(208,213,216, 255));
		shape.setLineStyle(ShapeLineStyle.Single);
		shape.setStrokeColor(new Color(208,213,216, 255));
//        shape.setStrokeWeight(0);

		Section section;
		HeaderFooter header;
		for (int n = 0; n < document.getSections().getCount(); n++) {
			section = document.getSections().get(n);
			//获取section的页眉
			header = section.getHeadersFooters().getHeader();
			Paragraph paragraph;
			if (header.getParagraphs().getCount() > 0) {
				//如果页眉有段落,取它第一个段落
				paragraph = header.getParagraphs().get(0);
			} else {
				//否则新增加一个段落到页眉
				paragraph = header.addParagraph();
			}
			for (int i = 0; i < 5; i++) {
				for (int j = 0; j < 4; j++) {
					if (j % 2 == 0) {
						// 打水印,复制艺术字并设置多行多列位置
						shape = (ShapeObject) shape.deepClone();

						shape.setVerticalPosition(50 + 180 * i);
						shape.setHorizontalPosition(20 + 120 * j);
						paragraph.getChildObjects().add(shape);
					} else {
						// 打图片水印,复制图片并设置多行多列位置
						picture = (DocPicture)picture.deepClone();
//                        picture.setVerticalPosition(180 * i);
//                        picture.setHorizontalPosition(120 * j);
						picture.setVerticalPosition(100 + 180 * i);
						picture.setHorizontalPosition(50 + 120 * j);
						paragraph.getChildObjects().add(picture);
					}
				}
			}
		}
	}
public void test5(){
//1.首先是拷贝一份模板
//2.接着创建表格
//3.填充表格数据
//4.添加水印,防止被盗
//5.保存文档
		//写到服务器中
		String path="服务器地址"
		document.saveToFile(path, FileFormat.Docx_2013);
	
		A  a = new A();
		//打开word文档
		XWPFDocument realDocment = a.openDoc(path);
		XWPFRun removeRun = realDocment.getParagraphs().get(0).getRuns().get(0);
		removeRun.setText("", 0);
		removeRun.setText("");
		//保存文档
		fileHelper.saveDocument(realDocment, pathWord);

		try {
			if (document != null){
				document.close();
			}
			if (realDocment != null){
				realDocment.close();
			}
		} catch (Exception e){
			logger.error("导出word文档,删除临时文件失败!!!");
		}
		}```
 /**
     * 打开word文档
     * @param path 文档所在路径
     * @return
     * @throws IOException
     */
    public XWPFDocument openDoc(String path) throws IOException {
        InputStream is = new FileInputStream(path);
        ZipSecureFile.setMinInflateRatio(-1.0d);
        return new XWPFDocument(is);
    }


更多推荐