SpringBoot动态导出word文档(完美实整教程 复制即可使用,不能实现你找我)
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureRenderData;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@RestController
public class WordController {
@GetMapping("/download-word")
public void downloadWord(HttpServletResponse response) throws IOException {
// 创建模板对象
XWPFTemplate template = XWPFTemplate.compile(new ByteArrayInputStream(createWord().toByteArray()));
// 模拟数据
Map<String, Object> data = new HashMap<>();
data.put("title", "标题");
data.put("image", new PictureRenderData(100, 100, "image.jpg"));
// 替换模板中的占位符
template.render(data);
// 写入输出流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
template.write(outputStream);
// 设置响应头
response.setHeader("Content-Disposition", "attachment;filename=example.docx");
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
// 写入响应流并下载
response.getOutputStream().write(outputStream.toByteArray());
response.getOutputStream().flush();
response.getOutputStream().close();
}
private ByteArrayOutputStream createWord() throws IOException {
// 创建Word文档
XWPFTemplate template = XWPFTemplate.compile("template.docx").render(new HashMap<>());
// 写入内存
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
template.write(outputStream);
// 关闭模板
template.close();
return outputStream;
}
}
这段代码使用了deepoove-poi
库来动态替换Word文档中的占位符,并下载生成的Word文档。在Spring Boot环境中,它创建了一个REST控制器,提供了一个接口来处理文档的下载。代码中包含了创建模板、替换数据、写入输出流、设置
评论已关闭