将html table 转成 excel

 1 package com.sun.office.excel;
 2
 3 /**
 4  * 跨行元素元数据
 5  *
 6  */
 7 public class CrossRangeCellMeta {
 8
 9     public CrossRangeCellMeta(int firstRowIndex, int firstColIndex, int rowSpan, int colSpan) {
10         super();
11         this.firstRowIndex = firstRowIndex;
12         this.firstColIndex = firstColIndex;
13         this.rowSpan = rowSpan;
14         this.colSpan = colSpan;
15     }
16
17     private int firstRowIndex;
18     private int firstColIndex;
19     private int rowSpan;// 跨越行数
20     private int colSpan;// 跨越列数
21
22     int getFirstRow() {
23         return firstRowIndex;
24     }
25
26     int getLastRow() {
27         return firstRowIndex + rowSpan - 1;
28     }
29
30     int getFirstCol() {
31         return firstColIndex;
32     }
33
34     int getLastCol() {
35         return firstColIndex + colSpan - 1;
36     }
37
38     int getColSpan(){
39         return colSpan;
40     }
41 }
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;
    }
}

基本思路:

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

时间: 2024-08-09 14:38:38

将html table 转成 excel的相关文章

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

当我们把web页面上的table导成excel形式时,有时候我们的数据需要以特定的格式呈现出来,这时候我们就需要给指定的单元格添加一些样式规格信息. 文本:vnd.ms-excel.numberformat:@ 日期:vnd.ms-excel.numberformat:yyyy/mm/dd 数字:vnd.ms-excel.numberformat:#,##0.00 货币:vnd.ms-excel.numberformat:¥#,##0.00 百分比:vnd.ms-excel.numberform

将table导出为Excel的标准无乱码写法

导出为Excel有很多种写法,对于一些复杂的格式,笔者喜欢在后台先拼成一个<table>,再使用Response输出. 如果数据中包含中文或者一些特殊字符,可很多不规范的写法都会导致页面乱码,这里就把一种(笔者认为)最标准的格式带给大家: Page p = HttpContext.Current.Handler as Page; p.Response.Clear(); p.Response.Buffer = true; p.Response.Charset = "UTF-8"

java 导出成EXCEL或XML

原文:java 导出成EXCEL或XML 源代码下载地址:http://www.zuidaima.com/share/1550463713774592.htm java 导出成EXCEL或XML, 纯手工写的. 复制到eclipse中去直接运行该类,就可以看到效果了. package com.zuidaima.file.exam.test; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import j

MySQL要导出成excel的方法

MySQL 要导出成 excel 文件很简单,执行类似这样的命令: select * from 某个表 into outfile  'd:/文件名.xls'; 上述命令你在服务器上执行,就导在服务器 D: 盘,若在客户端命令行方式执行,就导在客户端 D :盘 ,若在客户端通过 POST 方式执行,则导在服务器 D:盘.能导成功的大前提是你有登录权限 ,要有 select 权限,而且还要有 file 权限,如果没有 file 权限,你将无法执行 select ....into outfile 和

pdf怎么转换成excel格式 超简单

可编辑文档转换为不可编辑文档是非常简单的,比如将word或者excel转换成jpg或者pdf,office或者wps软件本身的最新版就自带有这个功能.但是如果我们要将PDF这种不可修改编辑的文档转换成可编辑的形式就会稍微麻烦一点,因为这种格式是任你怎么放大缩小都不会改变文件的排版方式,虽然阅读起来很方便.那怎么办呢?下面小编教给大家一个方法,可以将PDF转换成Excel格式,超简单! 把PDF格式的文件精确转换成EXCEL表格,这边我们可以选择一款叫"迅捷PDF转换器"的软件. (pd

财务必备技能 如何将pdf转换成excel

虽然pdf文件有各种的优点,但是编辑权限也是事实,将pdf转换成其他格式文件是不可避免的,之前小编给大家讲解过很多使用迅捷pdf转换器将pdf转换成word或是word转换成pdf的方法.今天就不局限于pdf和word的转换了,这里给大家一个新的转换形式,那就是pdf表格文件转换成excel,这可是财务必备技能之一,不会这种转换怎么看怎么亏. 如何将pdf转换成excel,pdf转excel操作步骤详解: 1.在迅捷pdf转换器的界面当中选择"文件转excel",之前我们在很多的文章中

Qt将table保存为excel(odbc方式)

首先是保存excel的方法,可参照: http://dzmlmszp.blog.163.com/blog/static/179271962014819111812531/ ok,进入正题. 现在我有一个table,如图: 图中的table可以是QTableWidget或QTableView 但是我需要隐藏最后一列,不要让用户看到,则在代码中加入: ui->tableWidget->setColumnCount(3); 运行中效果如下: 现在问题来了,怎样才能将我的table保存为excel?

php将数据库导出成excel的方法

<?php $fname = $_FILES['MyFile']['name']; $do = copy($_FILES['MyFile']['tmp_name'],$fname); if ($do) { echo"导入数据成功<br>"; } else { echo ""; } ?> <form ENCTYPE="multipart/form-data" ACTION="<?php echo&quo

.Net常用技巧_传入DataGrid直接导出成Excel

注:非调用OFFICE的DLL方法. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using Utility; using System.IO; names