java对word文档的操作-直接操作或poi工具包或freemarker+xml或html转word

1,java自带工具包实现对word的排版和写入

import java.awt.Color;    
import java.io.FileNotFoundException;    
import java.io.FileOutputStream;
import java.util.List;

import com.lowagie.text.Document;    
import com.lowagie.text.DocumentException;    
import com.lowagie.text.Font;    
import com.lowagie.text.PageSize;    
import com.lowagie.text.Paragraph;    
import com.lowagie.text.rtf.RtfWriter2;  
/**   
  * 创建word文档 步骤:    
  * 1,建立文档    
  * 2,创建一个书写器    
  * 3,打开文档    
  * 4,向文档中写入数据    
  * 5,关闭文档   
  */   
 public class Java2word {    
    
	  public Java2word() {    
	  }    
	    
	  /**   
	   * @param args   
	   */   
	  public static void main(String[] args) {   
		  creatDoc();
	  }
	  
	public static void creatDoc() {
		String path="E:\\test.doc";
		//设置纸张的大小  
		  Document document = new Document(PageSize.A4);   
		  try {    
				//创建word文档
			   RtfWriter2.getInstance(document,new FileOutputStream(path)); 
			   
			   //打开文档
			   document.open();    
			      
			    //创建段落
			Paragraph p = new Paragraph("带格式写入文档",new Font(Font.NORMAL, 10, Font.BOLD, new Color(0, 0, 0)) );   
				  //设置段落为居中对齐
				  p.setAlignment(Paragraph.ALIGN_CENTER);  
				  //写入段落
			      document.add(p);   
		      //关流
		      document.close(); 
		      System.out.println("end");
		  } catch (FileNotFoundException e) {    
		   e.printStackTrace();    
		  } catch (DocumentException e) {    
		   e.printStackTrace();    
		  } 
	}    
 }   

  2,java+poi实现对word的写入

所需jar包poi-3.17

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
 
public class MTest {
	@SuppressWarnings("resource")
	public static void main(String[] args) throws IOException {
		//新建一个文档  
	      XWPFDocument doc = new XWPFDocument();  
	      //创建一个段落  
	      XWPFParagraph para = doc.createParagraph();  
	       
	      //一个XWPFRun代表具有相同属性的一个区域。  
	      XWPFRun run = para.createRun();  
	      run.setBold(true); //加粗  
	      run.setText("加粗的内容");  
	      
	      run = para.createRun();  
	      run.setColor("FF0000");  
	      run.setText("红色的字。");
	      run=para.createRun();
	      run.setText("红色");
	      
	      OutputStream os = new FileOutputStream("D:\\MTest.doc");  
	      //把doc输出到输出流  
	      doc.write(os);  
	      doc.close(); 
	}
}

3,freemarker+xml

4,jsp或html转化成word

猜你喜欢

转载自www.cnblogs.com/news1997/p/10647144.html