poi操作word,简单写docx
在HWPF中换行符是"\013",在XWPF中是run.addBreak();也就是说word2007里面是没有直接的换行符的。
package com.lawmark.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.poi.xwpf.usermodel.Borders; import org.apache.poi.xwpf.usermodel.BreakClear; import org.apache.poi.xwpf.usermodel.BreakType; import org.apache.poi.xwpf.usermodel.LineSpacingRule; import org.apache.poi.xwpf.usermodel.ParagraphAlignment; import org.apache.poi.xwpf.usermodel.TextAlignment; import org.apache.poi.xwpf.usermodel.UnderlinePatterns; import org.apache.poi.xwpf.usermodel.VerticalAlign; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.struts2.ServletActionContext; import jcifs.smb.SmbFile; import jcifs.smb.SmbFileInputStream; public class demo { public static void main(String[] args) throws Exception { String str = redfile(); XWPFDocument doc = new XWPFDocument(); XWPFParagraph p1 = doc.createParagraph(); XWPFRun r4 = p1.createRun(); String s[] = str.split("\r\n"); for (int i = 0; i < s.length; i++) { r4.setText(s[i]); r4.addBreak(); } FileOutputStream out = new FileOutputStream("D:/simple.docx"); doc.write(out); out.close(); } public static String redfile(){ StringBuffer sb = new StringBuffer(); try { FileInputStream fis = new FileInputStream("E:\\zip\\lwk\\lwk001s002.txt"); InputStreamReader isr = new InputStreamReader(fis,"gb2312"); BufferedReader br = new BufferedReader(isr); String s = null; while ((s = br.readLine()) != null) { sb.append(s + "\r\n"); } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } }