当前位置:   article > 正文

java:poi导出word文档

java:poi导出word文档

导入依赖

<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>

  1. import org.apache.poi.xwpf.usermodel.*;
  2. import javax.servlet.http.HttpServletResponse;
  3. import java.io.IOException;
  4. import java.lang.reflect.Field;
  5. public class WordDocumentExporter {
  6. public void exportToWord(HttpServletResponse response, Object data) {
  7. XWPFDocument document = new XWPFDocument();
  8. // 创建表格
  9. XWPFTable table = document.createTable();
  10. XWPFTableRow headerRow = table.getRow(0);
  11. headerRow.getCell(0).setText("属性名");
  12. headerRow.addNewTableCell().setText("属性值");
  13. // 获取类的所有属性
  14. Field[] fields = data.getClass().getDeclaredFields();
  15. for (Field field : fields) {
  16. field.setAccessible(true);
  17. String fieldName = field.getName();
  18. String fieldValue = "";
  19. try {
  20. Object value = field.get(data);
  21. fieldValue = value != null ? value.toString() : "";
  22. } catch (IllegalAccessException e) {
  23. e.printStackTrace();
  24. }
  25. XWPFTableRow row = table.createRow();
  26. row.getCell(0).setText(fieldName);
  27. row.getCell(1).setText(fieldValue);
  28. }
  29. try {
  30. // 设置响应头
  31. response.setContentType("application/msword");
  32. response.setHeader("Content-Disposition", "attachment; filename=output.docx");
  33. // 输出到浏览器
  34. document.write(response.getOutputStream());
  35. response.getOutputStream().close();
  36. document.close();
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/684288
推荐阅读
相关标签
  

闽ICP备14008679号