/**
* @功能描述 POI 读取 Excel 转 HTML 支持 03xls 和 07xlsx 版本 包含样式
*/
public class PoiExcelUtil {
/**
*
* @param multipartFile
*/
public static void pdf2html(MultipartFile multipartFile, String fileName) {
// String path = "C:\\Users\\yugb\\Desktop\\tohtml.xlsx";
InputStream is = null;
String htmlExcel = null;
Writer wr=null;
try {
is = multipartFile.getInputStream();
Workbook wb = WorkbookFactory.create(is);//此WorkbookFactory在POI-3.10版本中使用需要添加dom4j
if (wb instanceof XSSFWorkbook) {
XSSFWorkbook xWb = (XSSFWorkbook) wb;
htmlExcel = getExcelInfo(xWb,true);
}else if(wb instanceof HSSFWorkbook){
HSSFWorkbook hWb = (HSSFWorkbook) wb;
htmlExcel = getExcelInfo(hWb,true);
}
String path = FileConst.UPLOAD_PATH + fileName;
File file=new File(path);
if(!file.exists()){
file.createNewFile();
}
wr=new FileWriter(file);
wr.write(htmlExcel);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(is!=null){
is.close();
}
if(wr!=null){
wr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 程序入口方法
* @param filePath 文件的路径
* @param isWithStyle 是否需要表格样式 包含 字体 颜色 边框 对齐方式
* @return <table>...</table> 字符串
*/
public String readExcelToHtml(String filePath , boolean isWithStyle){
InputStream is = null;
String htmlExcel = null;
try {
File sourcefile = new File(filePath);
is = new FileInputStream(sourcefile);
Workbook wb = WorkbookFactory.create(is);
if (wb instanceof XSSFWorkbook) {
XSSFWorkbook xWb = (XSSFWorkbook) wb;
htmlExcel = getExcelInfo(xWb,isWithStyle);
}else if(wb instanceof HSSFWorkbook){
HSSFWorkbook hWb = (HSSFWorkbook) wb;
htmlExcel = getExcelInfo(hWb,isWithStyle);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return htmlExcel;
}
public static String getExcelInfo(Workbook wb,boolean isWithStyle){
StringBuffer sb = new StringBuffer();
Sheet sheet = wb.getSheetAt(0);//获取第一个Sheet的内容
int lastRowNum = sheet.getLastRowNum();
Map<String, String> map[] = getRowSpanColSpanMap(sheet);
sb.append("<table style='border-collapse:collapse;' width='100%'>");
Row row = null; //兼容
Cell cell = null; //兼容
for (int rowNum = sheet.getFirstRowNum(); rowNum <= lastRowNum; rowNum++) {
row = sheet.getRow(rowNum);
if (row == null) {
sb.append("<tr><td > </td></tr>");
continue;
}
sb.append("<tr>");
int lastColNum = row.getLastCellNum();
poi excel 转 html
最新推荐文章于 2024-06-13 16:07:05 发布
这篇博客详细介绍了如何利用Apache POI库将Excel文件的内容转换为HTML格式,包括读取Excel数据、格式转换及生成HTML代码的过程,旨在帮助开发者实现数据的web展示。
摘要由CSDN通过智能技术生成