首页 > 代码库 > Java生成word文档

Java生成word文档

package word;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;

public class WordUtil {
    private static Document document;
    private static BaseFont baseFont;

    /**
     * 创建word,并设置纸张文档
     * @param filePath  文档路径  
     * @throws DocumentException
     * @throws IOException
     */
    private static void openWordFile(String filePath) throws DocumentException, IOException {
        document = new Document(PageSize.A4);
        RtfWriter2.getInstance(document, new FileOutputStream(filePath));
        document.open();
        baseFont = BaseFont.createFont();
    }

    /**
     * 设置标题
     * @param title  标题
     * @return
     * @throws DocumentException
     */
    private static boolean setTitle(String title) throws DocumentException {
        Font font = new Font(baseFont, 12, Font.BOLD);
        Paragraph pTitle = new Paragraph(title + "\n");
        pTitle.setFont(font);
        pTitle.setAlignment(Element.ALIGN_CENTER);
        return document.add(pTitle);
    }

    /**
     * 设置文档内容
     * @param content文档内容 
     * @return
     * @throws DocumentException
     */
    private static boolean setContent(String content) throws DocumentException {
        Font font = new Font(baseFont, 10, Font.NORMAL);
        Paragraph pContent = new Paragraph(content);
        //设置字体
        pContent.setFont(font);
        pContent.setAlignment(Element.ALIGN_LEFT);
        pContent.setSpacingAfter(5);
        pContent.setFirstLineIndent(20);
        return document.add(pContent);
    }

    /**
     * 创建丰富内容的word文档
     * @param filePath  文档保存地址
     * @param title  文档标题
     * @param contents  文档内容
     * @return
     */
    public static boolean CreateWordFile(String filePath, String title, List<String> contents) {
        boolean returnValue = http://www.mamicode.com/false;>


itext-rtf-2.1.7.jar,下载地址:http://download.csdn.net/detail/xuxu198899223/7717727


itext-2.1.7.jar 下载地址:http://download.csdn.net/detail/xuxu198899223/7717717