poi版本选3.10以上的 要不然插入图片 word会打不开
org.apache.poi
poi
3.11
org.apache.poi
poi-ooxml
3.11
stax-api
stax
我下面代码中imgurl是base64编码,让后转的图片,你们使用的话,直接替换成图片路径地址就可以了
headList参数表示表格头部需要合并的集合,如果相邻左右或者上下位置的内容相同,就会自动合并单元格
List> headList = new ArrayList<>();
headList.add(Arrays.asList(new String[]{"1","2","2","3","3","4","4","5"}));
headList.add(Arrays.asList(new String[]{"1","6","7","8","9","10","11","5"}));
headList.add(Arrays.asList(new String[]{"1","12","13","14","15","16","17","5"}));
dataList参数表示表格下方的数据集合,会根据headList中第一行的长度进行自动换行,传入 dataList参数的长度只要是headList(0)的长度的倍数即可.
其余的一些参数是我项目中使用到的,你们看着删一删就行了.
需要追加功能的话,创建一个WordExport 对象,然后一直调它的makeWord方法即可,需要生成新的word的话,重新创建对象.
package com.runstone.rsflow.word;
import com.runstone.system.util.ConstantParam;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.Logger;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;
import sun.misc.BASE64Decoder;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class WordExport {
private XWPFDocument document;
private FileOutputStream out;
private File file;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
/**
*
* @param title pdf的标题
* @param imgUrl 图片base64码
* @param filePath 要保存word的路径 例:d:/
* @param fileName word的文件名 例:1.pdf
* @param headList 表格头部的list数据
* @param dataList 表格下方的内容数据 按顺序填入集合中即可
* @param log
*/
public void makeWord (List title, List imgUrl, String filePath, String fileName,
List> headList, List dataList, String note,File file, Logger log){
fileName = fileName.replaceAll("/", "");
fileName = fileName.replaceAll("\\\\","");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String format = simpleDateFormat.format(new Date());
filePath += format+File.separator;
String imgName = filePath+ UUID.randomUUID().toString()+".png";
File f = new File(filePath);
if (!f.exists()){
f.mkdirs();
}
OutputStream imgOut = null;
try {
if (file.exists()){
//添加标题
XWPFParagraph titleParagraph2 = document.createParagraph();
//设置段落居中
titleParagraph2.setAlignment(ParagraphAlignment.CENTER);
XWPFRun titleParagraphRun2 = titleParagraph2.createRun();
titleParagraphRun2.setText(" ");
titleParagraphRun2.setFontSize(50);
}
/*对于每个new的OutputStream对象,只能被document.write()执行一次保存操作*/
/*所以每次写入新的段落都要新建OutputStream,否则执行第二次会报错*/
out = new FileOutputStream(file);
for (int i=0;i0){
//基本信息表格
XWPFTable imgTable = document.createTable((int)Math.ceil(Double.parseDouble(String.valueOf(imgUrl.size()))/2),imgUrl.size()>1?2:1);
imgTable.getCTTbl().getTblPr().unsetTblBorders();
int width = imgUrl.size()>1?190:505;
int height = imgUrl.size()>1?75:205;
XWPFParagraph paragraph = document.createParagraph();
int row = 0;
int col = 0;
for (int i=0;i> list,List dataList) throws Exception{
int length = list.get(0).size();
List>> aa = new ArrayList<>();
for (int i=0;i strings = list.get(i);
int colNum = 1;
List