有时需要将Excel展示在页面上,所以需要将Excel转化为html,这里封装一个工具类。

Excel和servlet访问效果如下图示:

工具类代码:

POIReadExcelToHtmlUtil.java

package com.alphajuns.utils;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test; import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*; /**
* excel转化为html工具类
*/
public class POIReadExcelToHtmlUtil { @Test
public void run() {
String filePath = "F:\\Test1.xlsx";
boolean isWithStyle = true;
List<Map<String, String>> excelMapList = POIReadExcelToHtmlUtil.readExcelToHtml(filePath, isWithStyle);
System.out.println(excelMapList);
} /**
* excel转html入口
* @param filePath
* @param isWithStyle
* @return
*/
public static List<Map<String, String>> readExcelToHtml(String filePath, boolean isWithStyle) {
List<Map<String, String>> excelInfoMapList = null;
// 文件对象
File file = new File(filePath);
// 文件流
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
// 创建工作簿
Workbook workbook = WorkbookFactory.create(inputStream);
// Excel类型
if (workbook instanceof HSSFWorkbook) {
//
HSSFWorkbook hssfWorkbook = (HSSFWorkbook) workbook;
// 获取Excel信息
excelInfoMapList = getExcelInfo(hssfWorkbook, isWithStyle);
} else if (workbook instanceof XSSFWorkbook) {
//
XSSFWorkbook xssfWorkbook = (XSSFWorkbook) workbook;
// 获取Excel信息
excelInfoMapList = getExcelInfo(xssfWorkbook, isWithStyle);
}
} catch (Exception e) {
e.printStackTrace();
} return excelInfoMapList;
} /**
* 获取Excel信息
* @param workbook
* @param isWithStyle
* @return
*/
private static List<Map<String, String>> getExcelInfo(Workbook workbook, boolean isWithStyle) {
List<Map<String, String>> htmlMapList = new ArrayList<Map<String, String>>();
// 获取所有sheet
int sheets = workbook.getNumberOfSheets();
// 遍历sheets
for (int sheetIndex = 0; sheetIndex < sheets; sheetIndex++) {
// 用于保存sheet信息
Map<String, String> sheetMap = new HashMap<String, String>();
// 获取sheet名
String sheetName = workbook.getSheetName(sheetIndex);
// 存储sheet名
sheetMap.put("sheetName", sheetName);
StringBuffer stringBuffer = new StringBuffer();
// 获取第一个sheet信息
Sheet sheet = workbook.getSheetAt(sheetIndex);
// 行数
int lastRowNum = sheet.getLastRowNum();
// 获取合并后的单元格行列坐标
Map<String, String> map[] = getRowSpanColSpan(sheet);
stringBuffer.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) {
stringBuffer.append("<tr><td>&nbsp;</td></tr>");
continue;
}
stringBuffer.append("<tr>");
// 列数
short lastCellNum = row.getLastCellNum();
for (int colNum = 0; colNum <= lastCellNum; colNum++) {
// 获取列
cell = row.getCell(colNum);
// 空白单元格
if (cell == null) {
stringBuffer.append("<td>&nbsp;</td>");
continue;
}
// 获取列值
String cellValue = getCellValue(cell);
if (map[0].containsKey(rowNum + "," + colNum)) {
String point = map[0].get(rowNum + "," + colNum);
map[0].remove(rowNum + "," + colNum);
int bottomRow = Integer.valueOf(point.split(",")[0]);
int bottomCol = Integer.valueOf(point.split(",")[1]);
int rowSpan = bottomRow - rowNum + 1;
int colSpan = bottomCol - colNum + 1;
stringBuffer.append("<td rowspan= '" + rowSpan + "' colSpan= '" + colSpan + "' ");
} else if (map[1].containsKey(rowNum + "," + colNum)) {
map[1].remove(rowNum + "," + colNum);
continue;
} else {
stringBuffer.append("<td ");
} // 判断是否包含样式
if (isWithStyle) {
// 处理单元格样式
dealExcelStyle(workbook, sheet, cell, stringBuffer);
} stringBuffer.append(">");
if (cellValue == null || "".equals(cellValue.trim())) {
stringBuffer.append(" &nbsp; ");
} else {
stringBuffer.append(cellValue.replace(String.valueOf((char) 160), "&nbsp;"));
}
stringBuffer.append("</td>");
}
stringBuffer.append("</tr>");
if (rowNum > 500) {
stringBuffer.append("<tr><td>数据量太大,请下载Excel查看更多数据</td></tr>");
break;
}
}
stringBuffer.append("</table>");
sheetMap.put("content", stringBuffer.toString());
htmlMapList.add(sheetMap);
}
return htmlMapList;
} /**
* 获取列值
* @param cell
* @return
*/
private static String getCellValue(Cell cell) {
String result = new String();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: // 数字类型
if (HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat simpleDateFormat = null;
// 时间
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
simpleDateFormat = new SimpleDateFormat("HH:mm");
} else {
// 日期
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
}
Date date = cell.getDateCellValue();
result = simpleDateFormat.format(date);
} else if (cell.getCellStyle().getDataFormat() == 58) {
// 处理自定义日期格式:m月d日(通过判断单元格格式的id解决,id值为58)
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
double value = cell.getNumericCellValue();
Date date = DateUtil.getJavaDate(value);
result = simpleDateFormat.format(date);
} else {
double value = cell.getNumericCellValue();
CellStyle cellStyle = cell.getCellStyle();
DecimalFormat decimalFormat = new DecimalFormat();
String temp = cellStyle.getDataFormatString();
// 单元格设置成常规
if (temp.equals("General")) {
decimalFormat.applyPattern("#");
}
result = decimalFormat.format(value);
}
break;
case Cell.CELL_TYPE_STRING: // 字符串
result = cell.getStringCellValue().toString();
break;
case Cell.CELL_TYPE_BLANK:
result = "";
break;
default:
result = "";
break;
}
return result;
} /**
* 合并单元格
* @param sheet
* @return
*/
private static Map<String, String>[] getRowSpanColSpan(Sheet sheet) {
Map<String, String> map0 = new HashMap<String, String>();
Map<String, String> map1 = new HashMap<String, String>();
// 获取合并后的单元格数量
int mergeNum = sheet.getNumMergedRegions();
CellRangeAddress range = null;
for (int i = 0; i < mergeNum; i++) {
range = sheet.getMergedRegion(i);
int topRow = range.getFirstRow();
int topCol = range.getFirstColumn();
int bottomRow = range.getLastRow();
int bottomCol = range.getLastColumn();
map0.put(topRow + "," + topCol, bottomRow + "," +bottomCol);
int tempRow = topRow;
while (tempRow <= bottomRow) {
int tempCol = topCol;
while (tempCol <= bottomCol) {
map1.put(tempRow + "," + tempCol, "");
tempCol++;
}
tempRow++;
}
map1.remove(topRow + "," + topCol);
}
Map[] map = {map0, map1};
return map;
} static String[] bordesr = { "border-top:", "border-right:", "border-bottom:", "border-left:" };
static String[] borderStyles = { "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid", "solid", "solid", "solid", "solid" }; /**
* 处理单元格样式
* @param wb
* @param sheet
* @param cell
* @param sb
*/
private static void dealExcelStyle(Workbook wb, Sheet sheet, Cell cell, StringBuffer sb) {
CellStyle cellStyle = cell.getCellStyle();
if (cellStyle != null) {
short alignment = cellStyle.getAlignment();
// 单元格内容的水平对齐方式
sb.append("align='" + convertAlignToHtml(alignment) + "' ");
short verticalAlignment = cellStyle.getVerticalAlignment();
// 单元格中内容的垂直排列方式
sb.append("valign='" + convertVerticalAlignToHtml(verticalAlignment) + "' "); if (wb instanceof XSSFWorkbook) { XSSFFont xf = ((XSSFCellStyle) cellStyle).getFont();
short boldWeight = xf.getBoldweight();
sb.append("style='");
sb.append("font-weight:" + boldWeight + ";"); // 字体加粗
sb.append("font-size: " + xf.getFontHeight() / 2 + "%;"); // 字体大小
int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
sb.append("width:" + columnWidth + "px;"); XSSFColor xc = xf.getXSSFColor();
if (xc != null && !"".equals(xc)) {
sb.append("color:#" + xc.getARGBHex().substring(2) + ";"); // 字体颜色
} XSSFColor bgColor = (XSSFColor) cellStyle.getFillForegroundColorColor();
if (bgColor != null && !"".equals(bgColor)) {
sb.append("background-color:#" + bgColor.getARGBHex().substring(2) + ";"); // 背景颜色
}
sb.append(getBorderStyle(0, cellStyle.getBorderTop(), ((XSSFCellStyle) cellStyle).getTopBorderXSSFColor()));
sb.append(getBorderStyle(1, cellStyle.getBorderRight(), ((XSSFCellStyle) cellStyle).getRightBorderXSSFColor()));
sb.append(getBorderStyle(2, cellStyle.getBorderBottom(), ((XSSFCellStyle) cellStyle).getBottomBorderXSSFColor()));
sb.append(getBorderStyle(3, cellStyle.getBorderLeft(), ((XSSFCellStyle) cellStyle).getLeftBorderXSSFColor())); } else if (wb instanceof HSSFWorkbook) { HSSFFont hf = ((HSSFCellStyle) cellStyle).getFont(wb);
short boldWeight = hf.getBoldweight();
short fontColor = hf.getColor();
sb.append("style='");
HSSFPalette palette = ((HSSFWorkbook) wb).getCustomPalette(); // 类HSSFPalette用于求的颜色的国际标准形式
HSSFColor hc = palette.getColor(fontColor);
sb.append("font-weight:" + boldWeight + ";"); // 字体加粗
sb.append("font-size: " + hf.getFontHeight() / 2 + "%;"); // 字体大小
String fontColorStr = convertToStardColor(hc);
if (fontColorStr != null && !"".equals(fontColorStr.trim())) {
sb.append("color:" + fontColorStr + ";"); // 字体颜色
}
int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
sb.append("width:" + columnWidth + "px;");
short bgColor = cellStyle.getFillForegroundColor();
hc = palette.getColor(bgColor);
String bgColorStr = convertToStardColor(hc);
if (bgColorStr != null && !"".equals(bgColorStr.trim())) {
sb.append("background-color:" + bgColorStr + ";"); // 背景颜色
}
sb.append(getBorderStyle(palette, 0, cellStyle.getBorderTop(), cellStyle.getTopBorderColor()));
sb.append(getBorderStyle(palette, 1, cellStyle.getBorderRight(), cellStyle.getRightBorderColor()));
sb.append(getBorderStyle(palette, 3, cellStyle.getBorderLeft(), cellStyle.getLeftBorderColor()));
sb.append(getBorderStyle(palette, 2, cellStyle.getBorderBottom(), cellStyle.getBottomBorderColor()));
} sb.append("' ");
}
} /**
* 垂直对齐方式
* @param verticalAlignment
* @return
*/
private static String convertVerticalAlignToHtml(short verticalAlignment) {
String valign = "middle";
switch (verticalAlignment) {
case CellStyle.VERTICAL_BOTTOM:
valign = "bottom";
break;
case CellStyle.VERTICAL_CENTER:
valign = "center";
break;
case CellStyle.VERTICAL_TOP:
valign = "top";
break;
default:
break;
}
return valign;
} /**
* 水平对齐方式
* @param alignment
* @return
*/
private static String convertAlignToHtml(short alignment) {
String align = "left";
switch (alignment) {
case CellStyle.ALIGN_LEFT:
align = "left";
break;
case CellStyle.ALIGN_CENTER:
align = "center";
break;
case CellStyle.ALIGN_RIGHT:
align = "right";
break;
default:
break;
}
return align;
} private static String getBorderStyle(int b, short s, XSSFColor xc) {
if (s == 0)
return bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
;
if (xc != null && !"".equals(xc)) {
String borderColorStr = xc.getARGBHex();// t.getARGBHex();
borderColorStr = borderColorStr == null || borderColorStr.length() < 1 ? "#000000" : borderColorStr.substring(2);
return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
} return "";
} private static String getBorderStyle(HSSFPalette palette, int b, short s, short t) {
if (s == 0)
return bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
;
String borderColorStr = convertToStardColor(palette.getColor(t));
borderColorStr = borderColorStr == null || borderColorStr.length() < 1 ? "#000000" : borderColorStr;
return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;"; } private static String convertToStardColor(HSSFColor hc) {
StringBuffer sb = new StringBuffer("");
if (hc != null) {
if (HSSFColor.AUTOMATIC.index == hc.getIndex()) {
return null;
}
sb.append("#");
for (int i = 0; i < hc.getTriplet().length; i++) {
sb.append(fillWithZero(Integer.toHexString(hc.getTriplet()[i])));
}
}
return sb.toString();
} private static String fillWithZero(String str) {
if (str != null && str.length() < 2) {
return "0" + str;
}
return str;
}
}

servlet和jsp:

Excel转html工具类的更多相关文章

  1. 一个基于POI的通用excel导入导出工具类的简单实现及使用方法

    前言: 最近PM来了一个需求,简单来说就是在录入数据时一条一条插入到系统显得非常麻烦,让我实现一个直接通过excel导入的方法一次性录入所有数据.网上关于excel导入导出的例子很多,但大多相互借鉴. ...

  2. Workbook导出excel封装的工具类

    在实际中导出excel非常常见,于是自己封装了一个导出数据到excel的工具类,先附上代码,最后会写出实例和解释.支持03和07两个版本的 excel. HSSF导出的是xls的excel,XSSF导 ...

  3. Excel解析easyexcel工具类

    Excel解析easyexcel工具类 easyexcel解决POI解析Excel出现OOM <!-- https://mvnrepository.com/artifact/com.alibab ...

  4. Java基础学习总结(49)——Excel导入导出工具类

    在项目的pom文件中引入 <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifac ...

  5. 导入导出Excel的Java工具类ExcelUtil

    在编写ExcelUtil之前,在网上查了一些资料.java中用来处理Excel的第三方开源项目主要就是POI和JXL.poi功能强大,但是比较耗资源,对于大数据量的导入导出性能不是太好:jxl功能简单 ...

  6. java下载Excel模板(工具类)

    一次文件下载记录 一次不成熟的文件下载操作记录,希望能对需要的人有所帮助. 1.前端代码 $("#downloadModel").click(function(){ var mod ...

  7. java中excel导入\导出工具类

    1.导入工具 package com.linrain.jcs.test; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import ...

  8. 【原创】POI操作Excel导入导出工具类ExcelUtil

    关于本类线程安全性的解释: 多数工具方法不涉及共享变量问题,至于添加合并单元格方法addMergeArea,使用ThreadLocal变量存储合并数据,ThreadLocal内部借用Thread.Th ...

  9. 通用Excel文件导出工具类

    1:Excel格式 2:ExcelUtil.java import java.io.ByteArrayOutputStream; import java.io.IOException; import ...

随机推荐

  1. less匹配模式

    less里面的匹配模式相当于js里面的if,但又不完全是,比如用css画一个三角 html <div class="sanjiao"></div> less ...

  2. Paper Reading:Mask RCNN

    Mask RCNN 论文:Mask R-CNN 发表时间:2018 发表作者:(Facebook AI Research)Kaiming He, Georgia Gkioxari, Piotr Dol ...

  3. Jmeter(一)非GUI模式压测(NON-GUI模式)结果解析TPS

    非GUI模式压测(NON-GUI模式)结果解析TPS 准备工作 从脚本已录制成功之后开始进行压测 安装Jmeter拓展插件 查看 Transactions per Second https://jme ...

  4. Spring入门篇——AOP基本概念

    1.什么是AOP及实现方式 什么是AOP AOP:Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术 主要 ...

  5. Jsp与JavaScript区别

    有时候会误以为这两个是同一个概念,但其实不是 Jsp全名为Java Server Pages(Java服务器页面),其根本是一个简化的Servlet设计,他实现了在Java当中使用HTML标签.Jsp ...

  6. httprunnermanager环境搭建 -----转

    转发自  https://www.cnblogs.com/tiechui2015/p/10017801.html  感谢大神 1,开源代码下载 这里的git下载地址是:https://github.c ...

  7. Java并发包--ConcurrentLinkedQueue

    转载请注明出处:http://www.cnblogs.com/skywang12345/p/3498995.html ConcurrentLinkedQueue介绍 ConcurrentLinkedQ ...

  8. 省选模拟赛 Problem 3. count (矩阵快速幂优化DP)

    Discription DarrellDarrellDarrell 在思考一道计算题. 给你一个尺寸为 1×N1 × N1×N 的长条,你可以在上面切很多刀,要求竖直地切并且且完后每块的长度都是整数. ...

  9. I have Flash Player installed, but I am unable to view Flash content in Chromium. How do I enable Flash Player to view this content?

    I have Flash Player installed, but I am unable to view Flash content in Chromium. How do I enable Fl ...

  10. redis系列(二):数据操作

    1.string类型 字符串类型是Redis中最为基础的数据存储类型,它在Redis中是二进制安全的,这便意味着该类型可以接受任何格式的数据,如JPEG图像数据或Json对象描述信息等.在Redis中 ...