思路分析
1.先生成Excel表格
2.把Excel表格插入到word文档中
代码
public String exportFile(HttpServletResponse response, OutFile outFile) throws IOException, XDocReportException {
try {
XWPFDocument doc = new XWPFDocument();// 创建Word文件
XWPFParagraph p = doc.createParagraph();// 新建一个段落
p.setAlignment(ParagraphAlignment.CENTER);// 设置段落的对齐方式
p.setBorderBottom(Borders.DOUBLE);//设置下边框
p.setBorderTop(Borders.DOUBLE);//设置上边框
p.setBorderRight(Borders.DOUBLE);//设置右边框
p.setBorderLeft(Borders.DOUBLE);//设置左边框
//查询数据库
List<OutFile> outFiles = outFileMapper.queryAll(outFile);
if (outFiles.size() > 0){
XWPFRun r = p.createRun();//创建段落文本
r.setText("重点工作“清单+闭环”管理台账(办公室人事科)");
r.setColor("000000");
r.setFontSize(20);
r.setBold(true);//设置为粗体
p = doc.createParagraph();// 新建一个段落
r = p.createRun();
r.setText("(5月份任务7件,已完成3件,持续推进2件,未完成1件,本月新增1件,累计7件)");
XWPFTable table= doc.createTable(outFiles.size() + 1, 8);//创建一个表格
table.getRow(0).getCell(0).setText("姓名");
table.getRow(0).getCell(1).setText("年龄");
table.getRow(0).getCell(2).setText("学校");
table.getRow(0).getCell(3).setText("住址");
table.getRow(0).getCell(4).setText("爱好");
table.getRow(0).getCell(5).setText("年级");
table.getRow(0).getCell(6).setText("班级");
table.getRow(0).getCell(7).setText("性别");
int index = 0;
for (int i = 0; i < outFiles.size(); i++) {
OutFile file = outFiles.get(i);
table.getRow(i + 1).getCell(0).setText(file.getTrno().toString());
table.getRow(i + 1).getCell(1 ).setText(file.getTaskdes());
table.getRow(i + 1).getCell(2).setText(file.getTasResource());
table.getRow(i + 1).getCell(3).setText(file.gettLeader());
table.getRow(i + 1).getCell(4).setText(file.getUnit() + "/" + file.getTaskHead());
table.getRow(i + 1).getCell(5).setText(file.getTaskEndDate().toString());
table.getRow(i + 1).getCell(6).setText(file.getDonePrecent());
table.getRow(i + 1).getCell(7).setText(file.getRemark());
}
path = "D:\\data\\2023\\test.doc";
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
System.out.println("文件已创建");
} else {
System.out.println("文件已存在");
}
FileOutputStream out = new FileOutputStream(path);
doc.write(out);
out.close();
}
return "成功";
} catch (IOException e) {
throw new RuntimeException(e);
}
}