java97Excel转07_java实现在线预览----poi操作excel转html及03、07版本兼容问题

poi操作excel转html及其兼容问题

excel03是读取文件整个内容转为字符串存进html,excel07是读取文件内容拼成字符串存进html

/**

* excel03转html

* filename:要读取的文件所在文件夹

* filepath:文件名

* htmlname:生成html名称

* path:html存放路径

* */

public static void PoiExcelToHtml (HttpServletRequest request,String filepath,String sourceid) throws Exception {

String htmlname="exportExcel"+sourceid+".html";

String path=request.getSession().getServletContext().getRealPath("/view/excel");

fileExists(path);//此方法是判断目录文件夹是否存在,这里就不贴了

String filename=request.getSession().getServletContext().getRealPath("/vod/mp4");

InputStream input=new FileInputStream(filename+"/"+filepath);

HSSFWorkbook excelBook=new HSSFWorkbook(input);

ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );

excelToHtmlConverter.processWorkbook(excelBook);//excel转html

Document htmlDocument =excelToHtmlConverter.getDocument();

ByteArrayOutputStream outStream = new ByteArrayOutputStream();//字节数组输出流

DOMSource domSource = new DOMSource (htmlDocument);

StreamResult streamResult = new StreamResult (outStream);

/** 将document中的内容写入文件中,创建html页面 */

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);

outStream.close();

String content = new String (outStream.toString("UTF-8"));

FileUtils.writeStringToFile(new File (path, htmlname), content, "utf-8");

}

/**

* excel07转html

* filename:要读取的文件所在文件夹

* filepath:文件名

* htmlname:生成html名称

* path:html存放路径

* */

public static void ExcelToHtml (HttpServletRequest request,String filepath,String sourceid) throws Exception{

String htmlname="exportExcel"+sourceid+".html";

String path=request.getSession().getServletContext().getRealPath("/view/excel");

String filename=request.getSession().getServletContext().getRealPath("/vod/mp4");

fileExists(path);

Workbook workbook = null;

InputStream is = new FileInputStream(filename+"/"+filepath);

try {

String html="";

workbook = new XSSFWorkbook(is);

for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {

Sheet sheet = workbook.getSheetAt(numSheet);

if (sheet == null) {

continue;

}

html+="=======================" + sheet.getSheetName() + "=========================
";

int firstRowIndex = sheet.getFirstRowNum();

int lastRowIndex = sheet.getLastRowNum();

html+="

Row firstRow = sheet.getRow(firstRowIndex);

for (int i = firstRow.getFirstCellNum(); i <= firstRow.getLastCellNum(); i++) {

Cell cell = firstRow.getCell(i);

String cellValue = getCellValue(cell, true);

html+="

" + cellValue + "";

}

//行

for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {

Row currentRow = sheet.getRow(rowIndex);

html+="

";

if(currentRow!=null){

int firstColumnIndex = currentRow.getFirstCellNum();

int lastColumnIndex = currentRow.getLastCellNum();

//列

for (int columnIndex = firstColumnIndex; columnIndex <= lastColumnIndex; columnIndex++) {

Cell currentCell = currentRow.getCell(columnIndex);

String currentCellValue = getCellValue(currentCell, true);

html+="

"+currentCellValue + "";

}

}else{

html+=" ";

}

html+="

";

}

html+="

";

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

DOMSource domSource = new DOMSource ();

StreamResult streamResult = new StreamResult (outStream);

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);

outStream.close();

FileUtils.writeStringToFile(new File (path, htmlname), html, "gbk");

}

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 读取单元格

*

*/

private static String getCellValue(Cell cell, boolean treatAsStr) {

if (cell == null) {

return "";

}

if (treatAsStr) {

cell.setCellType(Cell.CELL_TYPE_STRING);

}

if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {

return String.valueOf(cell.getBooleanCellValue());

} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {

return String.valueOf(cell.getNumericCellValue());

} else {

return String.valueOf(cell.getStringCellValue());

}

}这里我没贴读取图片的代码,因为我只能读取到所有图片但不能让图片按指定位置在页面显示,如果谁有简洁好用的代码可以分享给我,感激不尽

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java使用Apache POIExcel换为HTML并含图片,你可以使用Apache POI和ApacheI-OOXML依赖项来完成此操作下面是一个简单的示例代码: java import org.apache.poi.ss.usermodel.*; import org.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFPictureData; import java.io.*; import.util.Base64; public ExcelToHtmlConverter { static void main(String[] args) try { //读取Excel文件 fileInputStream = new FileInputStream("input.xlsx"); Workbook workbook = new XSSFWorkbook(fileInputStream); Sheet sheet = workbook.getSheetAt(0); // 创建HTML输出流 FileOutputStream fileOutputStream = new FileOutputStream("output.html"); PrintWriter printWriter = new PrintWriter(fileOutputStream); // 输出HTML头部 printWriter.println("<!DOCTYPE html>"); printWriter.println("<html>"); printWriter.println("<head>"); printWriter.println("<title>Excel to HTML</title>"); printWriter.println("</head>"); printWriter.println("<body>"); // 遍历每行 for (Row row : sheet) { printWriter.println("<tr>"); // 遍历每个单元格 for (Cell cell : row) { printWriter.print("<td>"); // 获取单元格内容 CellType cellType = cell.getCellType(); if (cellType == CellType.STRING) { printWriter.print(cell.getStringCellValue()); } else if (cellType == CellType.NUMERIC) { printWriter.print(cell.getNumericCellValue()); } else if (cellType == CellType.BOOLEAN) { printWriter.print(cell.getBooleanCellValue()); } // 检查单元格是否包含图片 if (cell instanceof XSSFSheet) { XSSFSheet xssfSheet = (XSSFSheet) sheet; for (POIXMLDocumentPart part : xssfSheet.getRelations()) { if (part instanceof XSSFPictureData) { XSSFPictureData pictureData = (XSSFPictureData) part; String base64Image = Base64.getEncoder().encodeToString(pictureData.getData()); printWriter.print("<img src=\"data:image/png;base64," + base64Image + "\"/>"); } } } printWriter.println("</td>"); } printWriter.println("</tr>"); } // 输出HTML尾部 printWriter.println("</body>"); printWriter.println("</html>"); printWriter.close(); System.out.println("Excel换为HTML成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 此代码将读取名为input.xlsx的Excel文件,并将其换为output.htmlHTML文件。在HTML,它将遍历每个单元格并将其内容输出为HTML表格。如果单元格包含图片,它将使用Base64编码将图片嵌入到HTML。 请注意,此代码仅处理XLSX格式的Excel文件。如果你的文件是XLS格式,你需要使用HSSFWorkbook和HSSFPictureData来进行处理。 希望这可以帮助到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值