You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import java.io.*;
import com.aspose.cells.*;
public class HtmlToExcel {
public static boolean getLicense() {
boolean result = false;
try {
InputStream is = HtmlToExcel.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String readFileContent(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
StringBuffer sbf = new StringBuffer();
try {
reader = new BufferedReader(new FileReader(file));
String tempStr;
while ((tempStr = reader.readLine()) != null) {
sbf.append(tempStr);
}
reader.close();
return sbf.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return sbf.toString();
}
public static void main(String[] args) throws Exception {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
String html = readFileContent("d:\\test.htm");
ByteArrayInputStream bais = new ByteArrayInputStream(html.getBytes());
String path = "d:\\test.xlsx";
FileOutputStream fos = new FileOutputStream(path);
// 加载选项html否则会出错
LoadOptions lo = new LoadOptions(LoadFormat.HTML);
Workbook workbook = new Workbook(bais, lo);
workbook.getWorksheets().get(0).setGridlinesVisible(true); // 显示网格线
workbook.getWorksheets().get(0).getHyperlinks().clear();// 清除超链接
workbook.getWorksheets().get(0).autoFitColumns();// 设置自适应列宽
// 输出保存
workbook.save(fos, SaveFormat.XLSX);
fos.close();
workbook.dispose();
}
}