首先说一下,本人发布的代码都是经过本人亲测,并且用在实际项目中。如果觉得可以,希望大家点个赞,谢谢大家。

有什么问题,大家评论出来,一起交流。好了,不废话了,下面来说一说这个东西怎么做。

网上也有许多版本,不过都不是我想要的,转出的html文件,要带表格,而且还能根据excel文件样式来生成html文件,不过太复杂的样式就支持不太强大了。

我采用poi去做这个功能,虽然还有jxl等其它方式,其它方式都有大的缺陷,有的不支持excel07版本,有的不能跨平台使用,这些都是很致命的缺点。

所以我采用poi去研究,我测试office和wps的excel版本都支持,并且兼容excel03及07以后版本,效果达到我的要求了,下面贴出源码,供大家一起学习。

jar包主要是这些 


import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
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;
  /**

           * @param filePath excel源文件文件的路径
* @param htmlPositon 生成的html文件的路径
* @param isWithStyle 是否需要表格样式 包含 字体 颜色 边框 对齐方式 */
public static String readExcelToHtml(String filePath ,String htmlPositon, 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) { //03版excel处理方法
XSSFWorkbook xWb = (XSSFWorkbook) wb;
htmlExcel = FileConverter.getExcelInfo(xWb,isWithStyle);
}else if(wb instanceof HSSFWorkbook){ //07及10版以后的excel处理方法
HSSFWorkbook hWb = (HSSFWorkbook) wb;
htmlExcel = FileConverter.getExcelInfo(hWb,isWithStyle);
}
writeFile(htmlExcel,htmlPositon);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return htmlPositon;
} private 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 ><nobr> </nobr></td></tr>");
continue;
}
sb.append("<tr>");
int lastColNum = row.getLastCellNum();
for (int colNum = 0; colNum < lastColNum; colNum++) {
cell = row.getCell(colNum);
if (cell == null) { //特殊情况 空白的单元格会返回null
sb.append("<td> </td>");
continue;
} String stringValue = getCellValue(cell);
if (map[0].containsKey(rowNum + "," + colNum)) {
String pointString = map[0].get(rowNum + "," + colNum);
map[0].remove(rowNum + "," + colNum);
int bottomeRow = Integer.valueOf(pointString.split(",")[0]);
int bottomeCol = Integer.valueOf(pointString.split(",")[1]);
int rowSpan = bottomeRow - rowNum + 1;
int colSpan = bottomeCol - colNum + 1;
sb.append("<td rowspan= '" + rowSpan + "' colspan= '"+ colSpan + "' ");
} else if (map[1].containsKey(rowNum + "," + colNum)) {
map[1].remove(rowNum + "," + colNum);
continue;
} else {
sb.append("<td ");
} //判断是否需要样式
if(isWithStyle){
dealExcelStyle(wb, sheet, cell, sb);//处理单元格样式
} sb.append("><nobr>");
if (stringValue == null || "".equals(stringValue.trim())) {
sb.append(" ");
} else {
// 将ascii码为160的空格转换为html下的空格( )
sb.append(stringValue.replace(String.valueOf((char) 160)," "));
}
sb.append("</nobr></td>");
}
sb.append("</tr>");
} sb.append("</table>");
return sb.toString();
} private static Map<String, String>[] getRowSpanColSpanMap(Sheet sheet) { Map<String, String> map0 = new HashMap<String, String>();
Map<String, String> map1 = new HashMap<String, String>();
int mergedNum = sheet.getNumMergedRegions();
CellRangeAddress range = null;
for (int i = 0; i < mergedNum; 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);
// System.out.println(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;
} /**
* 获取表格单元格Cell内容
* @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 sdf = null;
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
sdf = new SimpleDateFormat("HH:mm");
} else {// 日期
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
Date date = cell.getDateCellValue();
result = sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 58) {
// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil
.getJavaDate(value);
result = sdf.format(date);
} else {
double value = cell.getNumericCellValue();
CellStyle style = cell.getCellStyle();
DecimalFormat format = new DecimalFormat();
String temp = style.getDataFormatString();
// 单元格设置成常规
if (temp.equals("General")) {
format.applyPattern("#");
}
result = format.format(value);
}
break;
case Cell.CELL_TYPE_STRING:// String类型
result = cell.getRichStringCellValue().toString();
break;
case Cell.CELL_TYPE_BLANK:
result = "";
break;
default:
result = "";
break;
}
return result;
} /**
* 处理表格样式
* @param wb
* @param sheet
* @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();
String align = convertAlignToHtml(alignment);
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;");
sb.append("text-align:" + align + ";");//表头排版样式
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 align = convertAlignToHtml(alignment);
sb.append("text-align:" + align + ";");//表头排版样式
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 alignment
* @return
*/
private static String convertAlignToHtml(short alignment) { String align = "center";
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;
} /**
* 单元格中内容的垂直排列方式
* @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;
} 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;
} 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"}; 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 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 "";
}
/*
* @param content 生成的excel表格标签
* @param htmlPath 生成的html文件地址
*/
private static void writeFile(String content,String htmlPath){
File file2 = new File(htmlPath);
StringBuilder sb = new StringBuilder();
try {
file2.createNewFile();//创建文件 sb.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=GBK\"><title>Html Test</title></head><body>");
sb.append("<div>");
sb.append(content);
sb.append("</div>");
sb.append("</body></html>"); PrintStream printStream = new PrintStream(new FileOutputStream(file2)); printStream.println(sb.toString());//将字符串写入文件 } catch (IOException e) { e.printStackTrace();
} }

大家如果有什么不懂的,希望大家提出来,一起交流,一起进步。

excel转html 实现在线预览的更多相关文章

  1. .net core 实现excel 和 word 的在线预览

    最新在搞文件的在线预览,网上很多免费的方案都需要是电脑安装office的,这要就很麻烦:收费的插件又太贵了. 不过还是找到一款相对好用的免费在线预览插件. 直接在nuget上搜索ce.office.e ...

  2. C# 基于NPOI+Office COM组件 实现20行代码在线预览文档(word,excel,pdf,txt,png)

    由于项目需要,需要一个在线预览office的功能,小编一开始使用的是微软提供的方法,简单快捷,但是不符合小编开发需求, 就另外用了:将文件转换成html文件然后预览html文件的方法.对微软提供的方法 ...

  3. Print2flash在.NET(C#)中的使用,即文档在线预览

    office文档(word,excel,ppt)在线预览查看,有很多种方式,比如可以 1.调用weboffice组件,进行word预览,要求客户端安装word,仅适用IE, word2013, IE1 ...

  4. Print2flash在.NET(C#)64位中的使用,即文档在线预览

    转:http://www.cnblogs.com/flowwind/p/3411106.html Print2flash在.NET(C#)中的使用,即文档在线预览   office文档(word,ex ...

  5. 在线预览-Java 使用 Print2Flash 实现Office文档在线阅读

    近期项目上遇到一个需求是用户上传的文档进行在线浏览,之前有过一篇使用 OpenOffice 将 word 转换成 html 页面进行展示的.现在介绍一个新的工具那就是 Print2Flash .    ...

  6. Word/Excel 在线预览

    前言 近日项目中做到一个功能,需要上传附件后能够在线预览.之前也没做过这类似的,于是乎就查找了相关资料,.net实现Office文件预览大概有这几种方式: ① 使用Microsoft的Office组件 ...

  7. [Asp.net]常见word,excel,ppt,pdf在线预览方案,有图有真相,总有一款适合你!

    引言 之前项目需要,查找了office文档在线预览的解决方案,顺便记录一下,方便以后查询. 方案一 直接在浏览器中打开Office文档在页面上的链接.会弹出如下窗口: 优点:主流浏览器都支持. 缺点: ...

  8. ASP.NET MVC在线预览Excel、Word、TXT、PDF文件

    代码: using System; using System.Collections.Generic; using System.Linq; using System.Web; using Syste ...

  9. Atitit.office word  excel  ppt pdf 的web在线预览方案与html转换方案 attilax 总结

    Atitit.office word  excel  ppt pdf 的web在线预览方案与html转换方案 attilax 总结 1. office word  excel pdf 的web预览要求 ...

随机推荐

  1. 基于路由器物理接口的vlan间路由

    广播域之间来往的数据包都是路由器中继的,所以vlan间的通信业需要路由器提供中继服务,这称作vlan间路由,可以用路由器或三层交换机实现. 配置R1: r1(config)#inter fa0/0r1 ...

  2. [刷题]算法竞赛入门经典 3-7/UVa1368 3-8/UVa202 3-9/UVa10340

    书上具体所有题目:http://pan.baidu.com/s/1hssH0KO 都是<算法竞赛入门经典(第二版)>的题目,标题上没写(第二版) 题目:算法竞赛入门经典 3-7/UVa13 ...

  3. IO多路复用深入浅出

    前言 从零单排高性能问题,这次轮到异步通信了.这个领域入门有点难,需要了解UNIX五种IO模型和 TCP协议,熟练使用三大异步通信框架:Netty.NodeJS.Tornado.目前所有标榜异步的通信 ...

  4. jQuery手风琴菜单!!!!

    jQuery手风琴菜单 第一次发博客也不知道说点什么好,以前敲得一个手风琴菜单刚刚整理出来了,就来分享个大家 手风琴的排版 排版完事了,接下来就写样式吧,把自己喜欢的颜色或者是图片添加进来,就会变成你 ...

  5. 14、Iterator跟ListIterator的区别

    14.Iterator与ListIterator的区别 在使用List,Set的时候,为了实现对其数据的遍历,会经常使用到Iterator(跌代器).使用跌代器,不需要干涉其遍历的过程,只需要每次取出 ...

  6. web 直播&即时聊天------阿里云、融云(二)

    上一篇简要主要介绍了融云制作聊天室的基本方法,这次基本属于对上一篇的补充以及进阶...^_^... (ps:吐槽一下,加了三个融云的线下qq群,全部没人解决问题,也不知道建此群的意义,若是民间的话就当 ...

  7. java 空指针异常造成的原因有哪些

    实际上 空指针异常   也就是你用了一个没有实际值的对象 1. 某一对象没有被实例化,就拿来使用,如调用此对象的方法,会抛空指针异常. 2. 获取从别的对象传过来的对象为空 3. 数据库查询方面的空指 ...

  8. 016 多对多关联映射 单向(many-to-many)

    一般的设计中,多对多关联映射,需要一个中间表 Hibernate会自动生成中间表 Hibernate使用many-to-many标签来表示多对多的关联 多对多的关联映射,在实体类中,跟一对多一样,也是 ...

  9. Android 内存泄漏分析与解决方法

    在分析Android内存泄漏之前,先了解一下JAVA的一些知识 1. JAVA中的对象的创建 使用new指令生成对象时,堆内存将会为此开辟一份空间存放该对象 垃圾回收器回收非存活的对象,并释放对应的内 ...

  10. root用户不能修改iptable文件

    问题: 需要放通IP 端口  执行: vi /etc/sysconfig/iptables, 添加完成后,wq保存,提示文件只读无法保存!!! 解决步骤: 1.查看文件权限  ls -ld /etc/ ...