POI 把 excel 转 html

1.导入 maven项目

 


          org.apache.poi
          poi
          ${poi.version}
      


   org.apache.poi
   poi-ooxml
   ${poi-ooxml.version}



   org.apache.poi
   poi-scratchpad
   3.8

 

 

 

版本3.8以上

 

测试代码:

 

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.w3c.dom.Document;

/**
 * Created by fangchen on 2017/6/1.
 */
public class PoiUtil {
    public static void excelToHtml(String fileName)
            throws FileNotFoundException, IOException, ParserConfigurationException,
            TransformerConfigurationException, TransformerException {
        InputStream is = new FileInputStream(fileName);

        HSSFWorkbook excelBook = new HSSFWorkbook(is);

        ExcelToHtmlConverter ethc = new ExcelToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        ethc.setOutputColumnHeaders(false);
        ethc.setOutputRowNumbers(false);

        ethc.processWorkbook(excelBook);

        Document htmlDocument = ethc.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        out.close();

        String htmlStr = new String(out.toByteArray());

        htmlStr = htmlStr.replace("

Sheet1

", "") .replace("

Sheet2

", "") .replace("

Sheet3

", "") .replace("

Sheet4

", "") .replace("

Sheet5

", ""); System.out.println(htmlStr); } public static void main(String[] args) throws ParserConfigurationException, TransformerException, IOException { excelToHtml("D:\\固定资产流程.xls"); } }

 

 

 

 

你可能感兴趣的:(Java,其他)