使用技术
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.6.0-beta1</version>
</dependency>
演示
部分代码展示
@GetMapping(value = "/")
public ModelAndView index() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
modelAndView.addObject("weeklyList", weeklyService.findAllByWeekNum());
return modelAndView;
}
@RequestMapping(value = "/invite/create")
@ResponseBody
public Map createInvite(@Validated CreateInviteForm form) {
String weeklyNum = DateUtils.generateTime();
String creatorName = form.getCreatorName();
String base64InviteCode = Base32.encode((String.format("%s_%s", weeklyNum, creatorName)));
timedCache.put(StrUtil.join("_", "inviteCode", weeklyNum, creatorName), base64InviteCode);
String localAddressIp = NetUtil.getLocalhost().getHostAddress();
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("inviteLink", "http://" + localAddressIp + ":" + runPort + "/invite/" + base64InviteCode);
return ResponseUtils.success(resultMap);
}
@RequestMapping(value = "/invite/{inviteCode}")
public ModelAndView openInvite(@PathVariable @NotNull String inviteCode) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("write");
modelAndView.addObject("expire", false);
modelAndView.addObject("tip", "邀请链接会在24小时内过期, 请尽快填写!");
String decodeInviteCode = Base32.decodeStr(inviteCode);
String[] inviteCodeArray = StrUtil.split(decodeInviteCode, "_");
if (decodeInviteCode != null && inviteCodeArray.length == 2) {
String cacheKey = StrUtil.join("_", "inviteCode", inviteCodeArray[0], inviteCodeArray[1]);
String cacheValue = timedCache.get(cacheKey, false);
modelAndView.addObject("creatorName", inviteCodeArray[1]);
modelAndView.addObject("weekNum", inviteCodeArray[0]);
if (StrUtil.isEmpty(cacheValue)) {
modelAndView.addObject("expire", true);
modelAndView.addObject("tip", "邀请已经过期啦~");
}
} else {
modelAndView.addObject("expire", true);
modelAndView.addObject("tip", "Illegal Invite Code !");
}
return modelAndView;
}
@RequestMapping(value = "/submit", method = RequestMethod.POST)
@ResponseBody
public Map submit(@Validated SubmitForm form) {
Weekly weeklyReport = weeklyService.findByWeekNumAndStaffName(form.getWeekNum(), form.getStaffName());
if (weeklyReport == null) {
weeklyService.insert(form);
return ResponseUtils.success("保存成功");
} else {
weeklyReport.setLastWeekReport(form.getLastWeekReport());
weeklyReport.setNextWeekReport(form.getNextWeekReport());
weeklyService.update(weeklyReport);
return ResponseUtils.success("修改成功");
}
}
@RequestMapping(value = "/export", method = RequestMethod.POST)
public ResponseEntity<byte[]> export(HttpServletRequest request, HttpServletResponse response,
@NotNull String weekNum, @NotNull String inviteName) throws Exception {
System.out.println("invitename" + inviteName);
String fileName = StrUtil.join("_", "weekly", DateUtil.today()) + ".doc";
List<Weekly> resultList = weeklyService.findByWeekNum(weekNum, inviteName);
Map<String, Object> dataTables = new HashMap<>();
dataTables.put("title","周报");
dataTables.put("time", DateUtils.generateTime());
List<TableContent> tableContentList = new ArrayList<>();
for(Weekly weekly: resultList) {
TableContent tableContent = new TableContent();
tableContent.setName(weekly.getStaffName());
tableContent.setLastWeek(weekly.getLastWeekReport());
tableContent.setThisWeek(weekly.getNextWeekReport());
tableContentList.add(tableContent);
}
dataTables.put("content", tableContentList);
response.setContentType("application/msword;charset=utf-8");
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + fileName);
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(GenerateWeekUtils.createTable(dataTables), headers, statusCode);
return entity;
}
public class GenerateWeekUtils {
public static byte[] createTable(Map<String, Object> dataTables) throws Exception {
String title = (String) dataTables.get("title");
String time = (String) dataTables.get("time");
List<TableContent> tableContentList = (List<TableContent>) dataTables.get("content");
ByteArrayOutputStream baos;
try (XWPFDocument doc = new XWPFDocument()) {
XWPFParagraph p = doc.createParagraph();// 新建一个段落
p.setAlignment(ParagraphAlignment.CENTER);// 设置段落的对齐方式
XWPFRun r = p.createRun();//创建段落文本
r.setBold(true);//设置为粗体
r.setColor("000000");//设置颜色
r.setFontSize(25);
r.setText(title);
p = doc.createParagraph();// 新建一个段落
p.setBorderBottom(Borders.APPLES);//设置下边框
p.setAlignment(ParagraphAlignment.RIGHT);
r = p.createRun();
r.setText("日期: " + time);
p = doc.createParagraph();// 新建一个段落
XWPFTable table = doc.createTable(1, 3);//创建一个表格
setTableWidthAndHAlign(table, "8202", STJc.CENTER);
setTableHeight(table, 560, STVerticalJc.CENTER);
//create first row
XWPFTableRow tableRowOne = table.getRow(0);
tableRowOne.getCell(0).setText("名字");
tableRowOne.getCell(1).setText("上周");
tableRowOne.getCell(2).setText("本周");
tableRowOne.getCell(0).setColor("E2EFD9");
tableRowOne.getCell(1).setColor("E2EFD9");
tableRowOne.getCell(2).setColor("E2EFD9");
generateContent(table, tableContentList);
baos = new ByteArrayOutputStream();
doc.write(baos);//文档写入流
}
return baos.toByteArray();
// ByteArrayInputStream in = new ByteArrayInputStream(baos.toByteArray());
// saveTable(doc);
}
/**
* @Description: 设置表格总宽度与水平对齐方式
*/
private static void setTableWidthAndHAlign(XWPFTable table, String width,
STJc.Enum enumValue) {
CTTblPr tblPr = getTableCTTblPr(table);
// 表格宽度
CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();
if (enumValue != null) {
CTJc cTJc = tblPr.addNewJc();
cTJc.setVal(enumValue);
}
// 设置宽度
tblWidth.setW(new BigInteger(width));
tblWidth.setType(STTblWidth.DXA);
}
/**
* @Description: 得到Table的CTTblPr,不存在则新建
*/
private static CTTblPr getTableCTTblPr(XWPFTable table) {
CTTbl ttbl = table.getCTTbl();
// 表格属性
CTTblPr tblPr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl.getTblPr();
return tblPr;
}
/**
* 设置表格行高
* @param infoTable
* @param heigth 高度
* @param vertical 表格内容的显示方式:居中、靠右...
* @Author Huangxiaocong 2018年12月16日
*/
private static void setTableHeight(XWPFTable infoTable, int heigth, STVerticalJc.Enum vertical) {
List<XWPFTableRow> rows = infoTable.getRows();
for(XWPFTableRow row : rows) {
CTTrPr trPr = row.getCtRow().addNewTrPr();
//run.getCTR().addNewRPr().addNewHighlight().setVal(STHighlightColor.YELLOW);
CTHeight ht = trPr.addNewTrHeight();
ht.setVal(BigInteger.valueOf(heigth));
List<XWPFTableCell> cells = row.getTableCells();
for(XWPFTableCell tableCell : cells ) {
CTTcPr cttcpr = tableCell.getCTTc().addNewTcPr();
cttcpr.addNewVAlign().setVal(vertical);
}
}
}
private static void generateContent(XWPFTable table, List<TableContent> tableContentList) {
//create second row
for (TableContent tableContent: tableContentList) {
XWPFTableRow tableRowTwo = table.createRow();
setTableHeight(table,560, STVerticalJc.CENTER);
tableRowTwo.getCell(0).setText(tableContent.getName());
// tableRowTwo.getCell(1).setText(tableContent.getLastWeek());
// tableRowTwo.getCell(2).setText(tableContent.getThisWeek());
XWPFParagraph contentParagraph = tableRowTwo.getCell(1).getParagraphs().get(0);
contentParagraph.setAlignment(ParagraphAlignment.LEFT);
XWPFRun run = contentParagraph.createRun();
setWrap(tableContent.getLastWeek(), contentParagraph, run);
XWPFParagraph contentParagraph2 = tableRowTwo.getCell(2).getParagraphs().get(0);
contentParagraph2.setAlignment(ParagraphAlignment.LEFT);
XWPFRun run2 = contentParagraph2.createRun();
setWrap(tableContent.getThisWeek(), contentParagraph2, run2);
}
}
/**
* 设置表格内文字换行
*
* @param value 需要换行的内容
* @param paragraph 当前段落
* @param run
*/
private static void setWrap(Object value, XWPFParagraph paragraph, XWPFRun run) {
if (((String) value).indexOf("\n") > 0) {
//设置换行
String[] text = value.toString().split("\n");
run = paragraph.insertNewRun(0);
for (int f = 0; f < text.length; f++) {
if (f == 0) {
run.setText(text[f].trim());
} else {
// run.addCarriageReturn();//硬回车
// 换行
run.addBreak(BreakClear.LEFT);
run.setText(text[f].trim());
}
}
} else {
run.setText((String) value);
}
}
private static void saveTable(XWPFDocument doc) throws Exception {
OutputStream os = new FileOutputStream("d:\\sample.doc");
doc.write(os);
os.close();
}
}
代码链接
https://download.csdn.net/download/M18856018695/12561021
解压密码:123456