java向word写入数据
pom.xml
代码:
private static String fileDir = "/home/xdja/conf/edums_js/"; private static String errorWordFilePath = "importWordErrorDetails.doc"; private static String errorExcelFilePath = "importExcelErrorDetails.doc"; /** * 写导入题库错误文件类容 * @param fileDir 文件路径 * @param filePath 文件路径 * @param content 内容 * @param type 文件类型 1---excel 2 word; * @author niugang */ private void writerErrorFileContent(String fileDir, String filePath, List<String> content, String type) { XWPFDocument document = new XWPFDocument(); OutputStream stream = null; BufferedOutputStream bufferStream = null; try { File dir = new File(fileDir); if (!dir.exists()) { dir.mkdirs(); } stream = new FileOutputStream(new File(fileDir+filePath)); bufferStream = new BufferedOutputStream(stream, 1024); // 创建一个段落 XWPFParagraph p1 = document.createParagraph(); // 设置居中 p1.setAlignment(ParagraphAlignment.CENTER); XWPFRun r1 = p1.createRun(); // 是否加粗 r1.setBold(true); // 与下一行的距离 r1.setTextPosition(30); if (EdumsConstants.FILE_TYPE_XLS.equals(type)) { // 段落名称 r1.setText("EXCEL导入题目错误格式详解"); } if (EdumsConstants.FILE_TYPE_DOC.equals(type)) { // 段落名称 r1.setText("WORD导入题目错误格式详解"); } // 字体大小 r1.setFontSize(18);// 字体大小 // 增加换行 r1.addCarriageReturn(); // 创建第二个段落 XWPFParagraph p2 = document.createParagraph(); XWPFRun r2 = p2.createRun(); for (int i = 0; i < content.size(); i++) { r2.setText(i + 1 + "、" + content.get(i)); r2.addCarriageReturn(); } // 设置字体 r2.setFontFamily("仿宋"); r2.setFontSize(14);// 字体大小 document.write(stream); stream.close(); bufferStream.close(); } catch (Exception ex) { logger.error("写word或Excel错误文件失败:{}", ex.getMessage()); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); logger.error("写word或Excel错误文件失败:{}", e.getMessage()); } } if (bufferStream != null) { try { bufferStream.close(); } catch (IOException e) { e.printStackTrace(); logger.error("写word或Excel错误文件失败:{}", e.getMessage()); } } } }
效果:
相关博客:
https://www.cnblogs.com/dayuruozhi/p/6490793.html
https://www.cnblogs.com/unruly/archive/2017/09/06/7483858.html
微信公众号