当前位置:首页 » HTML/CSS

java xlsx转html

2018-04-13 15:21 本站整理 浏览(16)

 

       poi-scratchpad  包中提供了ExcelToHtmlConverter工具类可以实现xls文件转换为html的功能,但是无法实现xlsx转html。

       本代码重写了一遍ExcelToHtmlConverter,实现了xlsx转html。入口类为XssfExcelToHtmlConverter

 可以直接使用这个类中的main方法进行测试。源码在附件中,只要修改相应的包名即可,还要引入poi-scratchpad 和poi包。

 

 public static void main( String[] args )throws IOException, ParserConfigurationException, TransformerException{
        
    	String inputPath="/Users/xuwenfeng/Desktop/testexcel.xlsx";
        String outputPath="/Users/xuwenfeng/Desktop/testexcel.html";
    	
        args=new String[]{inputPath,outputPath};
        
    	if ( args.length < 2 )
        {
            System.err.println( "Usage: ExcelToHtmlConverter <inputFile.xls> <saveTo.html>" );
            return;
        }

        System.out.println( "Converting " + args[0] );
        System.out.println( "Saving output to " + args[1] );

        Document doc = XssfExcelToHtmlConverter.process( new File( args[0] ) );

        DOMSource domSource = new DOMSource( doc );
        StreamResult streamResult = new StreamResult( new File(args[1]) );

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        // TODO set encoding from a command argument
        serializer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" );
        serializer.setOutputProperty( OutputKeys.INDENT, "no" );
        serializer.setOutputProperty( OutputKeys.METHOD, "html" );
        serializer.transform( domSource, streamResult );
    }