public static void build(File tmpFile, Map<String, Object> contentMap, String exportFile) throws Exception { FileInputStream tempFileInputStream = new FileInputStream(tmpFile); HWPFDocument document = new HWPFDocument(tempFileInputStream); // 读取文本内容 Range bodyRange = document.getRange(); // 替换内容 for (Map.Entry<String, Object> entry : contentMap.entrySet()) { bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue().toString()); } // 导出到文件 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); document.write(byteArrayOutputStream); write(exportFile, byteArrayOutputStream); document.close(); }
write(pfs, mainBuf, STREAM_WORD_DOCUMENT); write(pfs, tableBuf, STREAM_TABLE_1); write(pfs, dataBuf, STREAM_DATA); } else { ByteArrayOutputStream bos = new ByteArrayOutputStream(100000); encryptBytes(mainBuf, FIB_BASE_LEN, bos); write(pfs, bos.toByteArray(), STREAM_WORD_DOCUMENT); bos.reset(); encryptBytes(tableBuf, _fib.getFibBase().getLKey(), bos); write(pfs, bos.toByteArray(), STREAM_TABLE_1); bos.reset(); encryptBytes(dataBuf, 0, bos); write(pfs, bos.toByteArray(), STREAM_DATA); bos.reset();
public static void build(InputStream inputStream, Map<String, Object> contentMap, String exportFile) throws Exception { // 打成jar包后会取不到模板文件,所以先这么处理 // 先将模板上传到临时目录,然后从临时目录取就没问题了 File file = new File("/opt/tmp/template.doc"); FileUtil.mkdirs(file); FileUtil.uploadFile(inputStream, file.getAbsolutePath()); // FileInputStream tempFileInputStream = new FileInputStream("/opt/tmp/template.doc"); HWPFDocument document = new HWPFDocument(tempFileInputStream); // 读取文本内容 Range bodyRange = document.getRange(); // 替换内容 for (Map.Entry<String, Object> entry : contentMap.entrySet()) { bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue().toString()); } // 导出到文件 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); document.write(byteArrayOutputStream); write(exportFile, byteArrayOutputStream); document.close(); if(file.exists()){ file.delete(); } }
try { URL url = new URL("localhost:8080/testproject/downloads/fileName.doc"); InputStream in = url.openStream(); fs = new POIFSFileSystem(in); HWPFDocument doc = new HWPFDocument(fs); newFileName = request.getRealPath("") + "/downloads/newFile.doc"; OutputStream writer = new FileOutputStream(newFileName); doc.getRange().replaceText("Location", "USA"); doc.write(writer); writer.close(); } catch(Exception e) { e.printStackTrace(); }
for(File file: folder.listFiles()) { if(file.getName().contains("docx")) { try { HWPFDocument docx= new HWPFDocument(new java.io.FileInputStream(file)); docx.getRange().insertBefore(toAppend); FileOutputStream fileOut = new FileOutputStream(file); docx.write(fileOut); fileOut.close(); } catch (IOException e) { e.printStackTrace(); } } }
import java.io.*; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.*; public class test { public static void main(String[] args) throws Exception { // POI apparently can't create a document from scratch, // so we need an existing empty dummy document HWPFDocument doc = new HWPFDocument(new FileInputStream("D:\\src.doc")); Range range = doc.getRange(); CharacterRun run = range .insertAfter("Text After copied file contents!"); run.setBold(true); OutputStream out = new FileOutputStream("D:\\result.doc"); doc.write(out); out.flush(); out.close(); } }
/** * Writes out the word file that is represented by an instance of this class. * * If the {@link File} exists, it will be replaced, otherwise a new one * will be created * * @param newFile The File to write to. * @throws IOException If there is an unexpected IOException from writing * to the File. * * @since 3.15 beta 3 */ @Override public void write(File newFile) throws IOException { POIFSFileSystem pfs = POIFSFileSystem.create(newFile); write(pfs, true); pfs.writeFilesystem(); }
/** * Writes out the word file that is represented by an instance of this class. * * For better performance when writing to files, use {@link #write(File)}. * If {@code stream} has a high cost/latency associated with each written byte, * consider wrapping the OutputStream in a {@link java.io.BufferedOutputStream} * to improve write performance. * * @param out The OutputStream to write to. * @throws IOException If there is an unexpected IOException from the passed * in OutputStream. */ @Override public void write(OutputStream out) throws IOException { POIFSFileSystem pfs = new POIFSFileSystem(); write(pfs, true); pfs.writeFilesystem( out ); }
@Override public byte[] handle(File originFile, String watermark, String color) throws IOException { watermark = StringUtils.isBlank(watermark)?DEFAULT_WATERMARK:watermark; color = StringUtils.isBlank(color)?DEFAULT_FONT_COLOR:color; if (originFile.getName().toLowerCase().endsWith("docx")) { try (InputStream in = new FileInputStream(originFile)){ XWPFDocument doc = new XWPFDocument(in); addWaterMark(doc, watermark, color); try (OutputStream out = new FileOutputStream(originFile)){ doc.write(out); doc.close(); } } return IOUtils.toByteArray(new FileInputStream(originFile)); } else if (originFile.getName().toLowerCase().endsWith("doc")) { try (InputStream in = new FileInputStream(originFile)){ HWPFDocument doc = new HWPFDocument(in); addWaterMark(doc, watermark, color); try (OutputStream out = new FileOutputStream(originFile)){ doc.write(out); doc.close(); } } return IOUtils.toByteArray(new FileInputStream(originFile)); } return null; }
/** * 创建Doc并保存 * * @param templatePath 模板doc路径 * @param parameters 参数和值 * //* @param imageParameters 书签和图片 * @param savePath 保存doc的路径 * @return */ public static void CreateDocFromTemplate(String templatePath, HashMap<String, String> parameters, //HashMap<String, String> imageParameters, String savePath) throws Exception { @Cleanup InputStream is = DocProducer.class.getResourceAsStream(templatePath); HWPFDocument doc = new HWPFDocument(is); Range range = doc.getRange(); //把range范围内的${}替换 for (Map.Entry<String, String> next : parameters.entrySet()) { range.replaceText("${" + next.getKey() + "}", next.getValue() ); } @Cleanup OutputStream os = new FileOutputStream(savePath); //把doc输出到输出流中 doc.write(os); } }
doc.write(out); out.close(); doc.close();
/** * Write out the word file that is represented by this class, to the * currently open {@link File}, via the writeable {@link POIFSFileSystem} * it was opened as. * * <p>This will fail (with an {@link IllegalStateException} if the * Document was opened read-only, opened from an {@link InputStream} * instead of a File, or if this is not the root document. For those cases, * you must use {@link #write(OutputStream)} or {@link #write(File)} to * write to a brand new document. * * @since 3.15 */ @Override public void write() throws IOException { validateInPlaceWritePossible(); // Update the Document+Properties streams in the file write(getDirectory().getFileSystem(), false); // Sync with the File on disk getDirectory().getFileSystem().writeFilesystem(); }
try { HWPFDocument document = [...]; // comes from somewhere Range range = document.getRange(); // Background shading of a paragraph ParagraphProperties pprops = new ParagraphProperties(); ShadingDescriptor shd = new ShadingDescriptor(); shd.setCvFore(Colorref.valueOfIco(0x07)); // yellow; ICO shd.setIpat(0x0001); // solid background; IPAT pprops.setShading(shd); Paragraph p1 = range.insertBefore(pprops, StyleSheet.NIL_STYLE); p1.insertBefore("shaded paragraph"); // Highlighting of individual characters Paragraph p2 = range.insertBefore(new ParagraphProperties(), StyleSheet.NIL_STYLE); CharacterRun cr = p2.insertBefore("highlighted text\r"); cr.setHighlighted((byte) 0x06); // red; ICO document.write([...]); // document goes to somewhere } catch (IOException e) { e.printStackTrace(); }