package com.app.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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;
/**
* @author chzhang
*
*/
public class PoiExcelToHtml {
public static void main(String[] args) {
convertExcel2Html("C:/Users/74217/Desktop/1.xls", "C:/Users/74217/Desktop/1.html", "GBK");
}
/**
*
* @param excelFilePath excel路径
* @param htmlFilePath html路径
* @param encoding 编码格式
*/
public static void convertExcel2Html(String excelFilePath, String htmlFilePath, String encoding) {
File excelFile = new File(excelFilePath);
File htmlFile = new File(htmlFilePath);
if (htmlFile.exists() && htmlFile.canRead())
return;
File htmlFileParent = new File(htmlFile.getParent());
InputStream is = null;
OutputStream out = null;
StringWriter writer = null;
try {
if (excelFile.exists()) {
if (!htmlFileParent.exists()) {
htmlFileParent.mkdirs();
}
is = new FileInputStream(excelFile);
HSSFWorkbook workBook = new HSSFWorkbook(is);
ExcelToHtmlConverter converter = new ExcelToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
converter.setOutputColumnHeaders(false);
converter.setOutputRowNumbers(false);
converter.processWorkbook(workBook);
writer = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, encoding);
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(new DOMSource(converter.getDocument()), new StreamResult(writer));
out = new FileOutputStream(htmlFile);
out.write(writer.toString().getBytes(encoding));
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
is = null;
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
out = null;
}
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
writer = null;
}
}
}
}