POI读写doc文件使用笔记
操作word文件,又可分为读写doc文件和docx文件(doc文件指的是旧版本,docx指的是2007+版本的),这里只总结读写doc文件的要点;
先概述读写doc文件时主要用到的类,
HWPFDocument:代表一个doc文件,主要的方法是getRange();
Range:代表一个文件的内容,可使用这个类对内容进行操作,主要的方法是replaceText(replacedText,repalcementText);
对doc文件进行编辑的常规做法是,先准备好一个模板,然后对doc文件进行填充时,把模板里面的文本替换成数据,这样进行填充;
例如,有以下的模板:
以下程序可向其填充数据,
public class Test { public static void main(String[] args) throws Exception{ String filePath = "D:"+File.separator+"test.doc"; InputStream input = new FileInputStream(filePath); HWPFDocument document = new HWPFDocument(input); Range range = document.getRange(); range.replaceText("$orderNum", "haha"); OutputStream output = new FileOutputStream("D:"+File.separator+"test2.doc"); document.write(output); output.close(); input.close(); } }
运行后,会在D盘生成test2.doc文件,里面的“$orderNum”被替换成“haha”;
注意:有时候会发现生成的doc文件时空白的,但是作为模版的文件并不是空白,那可能说过作为模板的doc文件底层发生了改变,不能正常地被读,那就应该换一份doc文件作为模板了。
浙公网安备 33010602011771号