HTML2DOC html转word

package com.eluotuo.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
 * 强html转换为doc
 * @author  wanglei
 * @version  [版本号, 2016年6月1日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class HtmlToDoc
{
    
    public static void main(String[] args)
        throws Exception
    {
        // TODO Auto-generated method stub
        byte[] bytes =
            writeWordFile("<body>hello<img src='https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=3832851394,4214400323&fm=58&s=39C718720E8EBE011B398BAC0300F024'></body>");
        FileUtils.writeByteArrayToFile(new File("d:/1.doc"), bytes);
    }
    
    /**
     * 读取html文件到word
     * 
     * @param html html文件的路径
     * @return word的二进制
     * @throws Exception
     */
    public static byte[] writeWordFile(String html)
        throws Exception
    {
        ByteArrayInputStream bais = null;
        FileOutputStream fos = null;
        ByteArrayOutputStream bos = null;
        try
        {
            
            
            byte b[] = html.getBytes("gbk");
            bais = new ByteArrayInputStream(b);
            POIFSFileSystem poifs = new POIFSFileSystem();
            DirectoryEntry directory = poifs.getRoot();
            bos = new ByteArrayOutputStream();
            DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
            poifs.writeFilesystem(bos);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (fos != null)
            {
                fos.close();
            }
               
            if (bais != null)
            {
                bais.close();
            }
            if (bos != null)
            {
                bos.close();
            }
        }
        return bos.toByteArray();
    }
    
}
PS 上面的解决方案只能在微软word中打开 在 wps中打开会出问题
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值