jar包依赖
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.8</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.8</version> </dependency>
/**
* 导出上报文件
* @param father 数据
* @param fileNmae 导出文件的名称
* @param <T>
* @return
* @throws Exception
*/
public static <T> String downloadDocx(T father, String fileNmae) throws Exception
{
//这是公司内部读取文件的方法 你可以用正常的写
FileInputStream stream = new FileInputStream(ResourceUtils.getFile(EXCELFORMATSTRING));
XWPFDocument doc = new XWPFDocument(stream);// 创建Word文件
for (XWPFTable table : doc.getTables())// 遍历表格
{
for (XWPFTableRow row : table.getRows())
{
for (XWPFTableCell cell : row.getTableCells())
{
String text = cell.getText();
System.out.println(text);
if (text.contains("【"))
{
text = text.substring(1, text.length() - 1);
text = getVal(father,text,"yyyy-MM-dd");
cell.removeParagraph(0);
XWPFParagraph pIO = cell.addParagraph();
XWPFRun rIO = pIO.createRun();
rIO.setFontFamily("宋体");
rIO.setFontSize(9);
rIO.setText(text);
}
}
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();// 二进制OutputStream
doc.write(baos);// 文档写入流
ByteArrayInputStream in = new ByteArrayInputStream(baos.toByteArray());
// 这是公司内部方法 导出文件 你可以根据实际情况操作 反正流你已经拿到了
String fileId = ExportFileUtil.saveFileToTemp(in, FilenameUtils.getExtension(fileNmae));
return fileId;
}
/**
* 根据属性名称 返回属性值
* @param father
* @param name
* @param <T>
* @return
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public static <T> String getVal(T father, String name,String pattern) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException
{
Class<?> fatherClass = father.getClass();
Method method = fatherClass.getDeclaredMethod("get" + upperHeadChar(name));
Object obj = method.invoke(father);
if (obj instanceof Date)
{
Date date = (Date) obj;
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
obj = formatter.format(date);
}
return Func.parseStr(obj);
}
/**
* 首字母大写,in:deleteDate,out:DeleteDate
*/
public static String upperHeadChar(String in)
{
String head = in.substring(0, 1);
String out = head.toUpperCase() + in.substring(1, in.length());
return out;
}
模板就是这样的

原文:https://www.cnblogs.com/closeIt/p/12667162.html