一、前端
点击按钮直接下载
const param1 = 'xxx';
const url = `${api}/v1/${getToken()}/controllerName/generateWord?param1 =${param1 }&token=${getAccessToken()}`;
window.location.href = url;
二、后台核心代码
// 将表格转换为Word文档
XWPFDocument document = new XWPFDocument();
// 新建一个段落
XWPFParagraph p = document.createParagraph();
// 设置段落的对齐方式
p.setAlignment(ParagraphAlignment.CENTER);
//创建段落文本
XWPFRun r = p.createRun();
r.setText( "这是一行内容");
r.setBold(true);//设置为粗体
r.setFontSize(18);//设置字体大小
//创建表格
XWPFTable table = document.createTable(5, 6);//5行6列的表格
for (int i = 0; i < dataList10.size() + 1; i++) {
XWPFTableRow tableRow = table.getRow(i);
for(int j = 0; j < dateSet1.size(); j++){
XWPFTableCell cell = tableRow.getCell(j);
if(i == 0){
//表头
cell.setText(String.valueOf(dateSet1.get(j).get("label")));
}else{
if(j == 0){
//第一列字段名
cell.setText("第"+i+"行");
}else{
//数据
cell.setText("数据"+i+j);
}
}
}
}
OutputStream out = null;
try {
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 保存Word文档
out = response.getOutputStream();
document.write(out);
out.close();
workbook.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
out.close();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}//end