package com.sun.office.excel;

 /**
* 跨行元素元数据
*
*/
public class CrossRangeCellMeta { public CrossRangeCellMeta(int firstRowIndex, int firstColIndex, int rowSpan, int colSpan) {
super();
this.firstRowIndex = firstRowIndex;
this.firstColIndex = firstColIndex;
this.rowSpan = rowSpan;
this.colSpan = colSpan;
} private int firstRowIndex;
private int firstColIndex;
private int rowSpan;// 跨越行数
private int colSpan;// 跨越列数 int getFirstRow() {
return firstRowIndex;
} int getLastRow() {
return firstRowIndex + rowSpan - 1;
} int getFirstCol() {
return firstColIndex;
} int getLastCol() {
return firstColIndex + colSpan - 1;
} int getColSpan(){
return colSpan;
}
}
package com.sun.office.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element; /**
* 将html table 转成 excel
*
* 记录下来所占的行和列,然后填充合并
*/
public class ConvertHtml2Excel {
public static void main(String[] args) {
byte[] bs = null;
try {
FileInputStream fis = new FileInputStream(new File(ConvertHtml2Excel.class.getResource("./a.html").getPath()));
bs = new byte[fis.available()];
fis.read(bs);
fis.close();
} catch (Exception e1) {
e1.printStackTrace();
}
String c = new String(bs);
HSSFWorkbook wb = table2Excel(c);
try {
FileOutputStream fos = new FileOutputStream(new File("1.xls"));
wb.write(fos);
fos.flush();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } /**
* html表格转excel
*
* @param tableHtml 如
* <table>
* ..
* </table>
* @return
*/
public static HSSFWorkbook table2Excel(String tableHtml) {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
List<CrossRangeCellMeta> crossRowEleMetaLs = new ArrayList<CrossRangeCellMeta>();
int rowIndex = 0;
try {
Document data = DocumentHelper.parseText(tableHtml);
// 生成表头
Element thead = data.getRootElement().element("thead");
HSSFCellStyle titleStyle = getTitleStyle(wb);
if (thead != null) {
List<Element> trLs = thead.elements("tr");
for (Element trEle : trLs) {
HSSFRow row = sheet.createRow(rowIndex);
List<Element> thLs = trEle.elements("th");
makeRowCell(thLs, rowIndex, row, 0, titleStyle, crossRowEleMetaLs);
rowIndex++;
}
}
// 生成表体
Element tbody = data.getRootElement().element("tbody");
if (tbody != null) {
HSSFCellStyle contentStyle = getContentStyle(wb);
List<Element> trLs = tbody.elements("tr");
for (Element trEle : trLs) {
HSSFRow row = sheet.createRow(rowIndex);
List<Element> thLs = trEle.elements("th");
int cellIndex = makeRowCell(thLs, rowIndex, row, 0, titleStyle, crossRowEleMetaLs);
List<Element> tdLs = trEle.elements("td");
makeRowCell(tdLs, rowIndex, row, cellIndex, contentStyle, crossRowEleMetaLs);
rowIndex++;
}
}
// 合并表头
for (CrossRangeCellMeta crcm : crossRowEleMetaLs) {
sheet.addMergedRegion(new CellRangeAddress(crcm.getFirstRow(), crcm.getLastRow(), crcm.getFirstCol(), crcm.getLastCol()));
}
} catch (DocumentException e) {
e.printStackTrace();
} return wb;
} /**
* 生产行内容
*
* @return 最后一列的cell index
*/
/**
* @param tdLs th或者td集合
* @param rowIndex 行号
* @param row POI行对象
* @param startCellIndex
* @param cellStyle 样式
* @param crossRowEleMetaLs 跨行元数据集合
* @return
*/
private static int makeRowCell(List<Element> tdLs, int rowIndex, HSSFRow row, int startCellIndex, HSSFCellStyle cellStyle,
List<CrossRangeCellMeta> crossRowEleMetaLs) {
int i = startCellIndex;
for (int eleIndex = 0; eleIndex < tdLs.size(); i++, eleIndex++) {
int captureCellSize = getCaptureCellSize(rowIndex, i, crossRowEleMetaLs);
while (captureCellSize > 0) {
for (int j = 0; j < captureCellSize; j++) {// 当前行跨列处理(补单元格)
row.createCell(i);
i++;
}
captureCellSize = getCaptureCellSize(rowIndex, i, crossRowEleMetaLs);
}
Element thEle = tdLs.get(eleIndex);
String val = thEle.getTextTrim();
if (StringUtils.isBlank(val)) {
Element e = thEle.element("a");
if (e != null) {
val = e.getTextTrim();
}
}
HSSFCell c = row.createCell(i);
if (NumberUtils.isNumber(val)) {
c.setCellValue(Double.parseDouble(val));
c.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
} else {
c.setCellValue(val);
}
c.setCellStyle(cellStyle);
int rowSpan = NumberUtils.toInt(thEle.attributeValue("rowspan"), 1);
int colSpan = NumberUtils.toInt(thEle.attributeValue("colspan"), 1);
if (rowSpan > 1 || colSpan > 1) { // 存在跨行或跨列
crossRowEleMetaLs.add(new CrossRangeCellMeta(rowIndex, i, rowSpan, colSpan));
}
if (colSpan > 1) {// 当前行跨列处理(补单元格)
for (int j = 1; j < colSpan; j++) {
i++;
row.createCell(i);
}
}
}
return i;
} /**
* 获得因rowSpan占据的单元格
*
* @param rowIndex 行号
* @param colIndex 列号
* @param crossRowEleMetaLs 跨行列元数据
* @return 当前行在某列需要占据单元格
*/
private static int getCaptureCellSize(int rowIndex, int colIndex, List<CrossRangeCellMeta> crossRowEleMetaLs) {
int captureCellSize = 0;
for (CrossRangeCellMeta crossRangeCellMeta : crossRowEleMetaLs) {
if (crossRangeCellMeta.getFirstRow() < rowIndex && crossRangeCellMeta.getLastRow() >= rowIndex) {
if (crossRangeCellMeta.getFirstCol() <= colIndex && crossRangeCellMeta.getLastCol() >= colIndex) {
captureCellSize = crossRangeCellMeta.getLastCol() - colIndex + 1;
}
}
}
return captureCellSize;
} /**
* 获得标题样式
*
* @param workbook
* @return
*/
private static HSSFCellStyle getTitleStyle(HSSFWorkbook workbook) {
short titlebackgroundcolor = HSSFColor.GREY_25_PERCENT.index;
short fontSize = 12;
String fontName = "宋体";
HSSFCellStyle style = workbook.createCellStyle();
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setBorderBottom((short) 1);
style.setBorderTop((short) 1);
style.setBorderLeft((short) 1);
style.setBorderRight((short) 1);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(titlebackgroundcolor);// 背景色 HSSFFont font = workbook.createFont();
font.setFontName(fontName);
font.setFontHeightInPoints(fontSize);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
return style;
} /**
* 获得内容样式
*
* @param wb
* @return
*/
private static HSSFCellStyle getContentStyle(HSSFWorkbook wb) {
short fontSize = 12;
String fontName = "宋体";
HSSFCellStyle style = wb.createCellStyle();
style.setBorderBottom((short) 1);
style.setBorderTop((short) 1);
style.setBorderLeft((short) 1);
style.setBorderRight((short) 1); HSSFFont font = wb.createFont();
font.setFontName(fontName);
font.setFontHeightInPoints(fontSize);
style.setFont(font);
return style;
}
}

基本思路:

  逐行遍历,记录下单元格所占的行和列,根据行列去填充空格,合并单元格

将html table 转成 excel的更多相关文章

  1. MVC 将视图页table导出成excel

    前台代码: <table class="tablelist" id="myTable">    <thead>        <t ...

  2. js实现把网页table导成Excel

    //导出excel function exportExcel(DivID,strTitle){ if(DivID==null) { return false; } var jXls, myWorkbo ...

  3. js实现把网页table导成Excel(bootstrap、JqGrid、Json)

    方案一:支持IE //导出excel function exportExcel(DivID,strTitle){ if(DivID==null) { return false; } var jXls, ...

  4. js中的table导出成Excel表格

    首先判断手否是IE,原因在于IE导出我用的是ActiveXObject,判断的方式很简单,只需要拿到window.navigator.userAgent即可进行判断,代码如下 function get ...

  5. C#将html table 导出成excel实例

    public void ProcessRequest (HttpContext context) { string elxStr = "<table><tbody>& ...

  6. 前端Table数据导出Excel使用HSSFWorkbook(Java)

    一.实现原理: 1. 前端查询列表数据并渲染至table(<table>...</table>)表格 2. 表格html代码传输至后台 3. 后台把html转成Excel输出流 ...

  7. web利用table表格生成excel格式问题

    当我们把web页面上的table导成excel形式时,有时候我们的数据需要以特定的格式呈现出来,这时候我们就需要给指定的单元格添加一些样式规格信息. 文本:vnd.ms-excel.numberfor ...

  8. Html Table用JS导出excel格式问题 导出EXCEL后单元格里的000412341234会变成412341234 7-14 会变成 2018-7-14(7月14) 自定义格式 web利用table表格生成excel格式问题 js导出excel增加表头、mso-number-format定义数据格式 数字输出格式转换 mso-number-format:"\@"

    Html Table用JS导出excel格式问题 我在网上找的JS把HTML Tabel导出成EXCEL.但是如果Table里的数字内容为0开的的导成Excel后会自动删除0,我想以text的格式写入 ...

  9. 【ASP.NET】C# 将HTML中Table导出到Excel(TableToExcel)

    首先,说下应用场景 就是,把页面呈现的Table 导出到Excel中.其中使用的原理是 前台使用ajax调用aspx后台,传递过去参数值,导出.使用的组件是NPOI. 前台调用: <script ...

随机推荐

  1. 番外篇--Moddule Zero介绍

    1.1 ABPZero - 概述 介绍 微软ASP.NET身份框架 权限 会话 角色管理 默认角色 用户管理 多租户 设置管理 审计日志 1.1.1 介绍 Modulde Zero实现了ASP.NET ...

  2. Spark高可用集群搭建

    Spark高可用集群搭建 node1    node2    node3   1.node1修改spark-env.sh,注释掉hadoop(就不用开启Hadoop集群了),添加如下语句 export ...

  3. SQL语句order by两个字段同时排序。

    ORDER BY  后可加2个字段,用英文逗号隔开.理解:对两个字段都排序,并不是之排序其中的一个字段: f1用升序, f2降序,sql该这样写 ORDERBY  f1, f2  DESC 也可以这样 ...

  4. ThinkPhp5.0_文件上传

    ===================================================================== 路径: F:\wamp\www\public\uploads ...

  5. 对[UIApplication sharedApplication]理解

    [ sharedApplication]返回UIApplication * application = nil; +(UIApplication*) shareApplication{ if(appl ...

  6. bug 对应

    异常1:not-null property references a null or transient value解决方法:将“一对多”关系中的“一”方,not-null设置为false http: ...

  7. node.js核心模块

    全局对象 global 是全局变量的宿主 全局变量 在最外层定义的 全局对象的属性 隐士定义的变量(未定义直接赋值的变量) 当定义一个全局变量时 这个变量同时也会成为全局对象的属性 反之亦然 注意: ...

  8. Jmeter_接口自动化基础流程概述

    这里补一篇基础的操作吧,不然总觉得没底! 1:创建一个线程组   2:添加一个cookie管理器   33333 3:设置你的信息头管理器:application/json;text/plain;ch ...

  9. spark-遇到问题小结

     经常会遇到 类似 shuffle 0 的错误,或者 connect refuse .主要是shuffle 导致内存不足引起的.shuffle 分为 shuffle read 和write . 1. ...

  10. 【转】SHELL variables default value, ${var:-DEFAULT}和${var=DEFAULT}的一点区别

    ${var:-DEFAULT}和${var=DEFAULT}的区别: ${var:-DEFAULT} If var not set or is empty, evaluate expression a ...