您的位置:首页 > Web前端 > HTML

将html中table的内容导出为excel

2015-12-14 15:24 609 查看
public void SDC() throws FileNotFoundException, UnsupportedEncodingException{
String htmlTable = getPara("htmlTable","");
String tname = getPara("tname","");
TableToExcelUtil tu = new TableToExcelUtil();

htmlTable = "<table>"+htmlTable+"</table>";
//		System.out.println(htmlTable.trim().replace("\n",""));
String url = tu.createExcelFormTable(tname, htmlTable.trim().replace("\n",""), 0,this.getRequest());
if(url != ""){
setAttr("success", url);
}else{
setAttr("fail", "导出失败");
}
renderJson();
}


public class TableToExcelUtil {
/**
* 导出excel表格二维数组
* @param sheetName 文件名称
* @param html 网页table数据(连带标签)
* @param headNum 是否为头表
* @param request
* @return
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
* by yanqingwen
*/
public String createExcelFormTable(String sheetName,String html,int headNum,HttpServletRequest request) throws FileNotFoundException, UnsupportedEncodingException{
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName);
HSSFCellStyle headStyle = this.createHeadStyle(wb);
HSSFCellStyle bodyStyle = this.createBodyStyle(wb);

String projectDic = request.getSession().getServletContext().getRealPath("/excel/")+File.separatorChar;
projectDic = projectDic.replace("\\","/");
String fileName = sheetName+".xls";
//String fileName = "table.xls";

FileOutputStream os = new FileOutputStream(projectDic + fileName);
SAXBuilder sb = new SAXBuilder();
ByteArrayInputStream is = new ByteArrayInputStream(html.getBytes("UTF-8"));

String url = "excel/" + fileName;
try {
org.jdom.Document document = sb.build(is);
//获取table节点
Element root = document.getRootElement();
//获取tr的list
List<Element> trList = root.getChildren("tr");

int[][] area = getCellArea(trList);
//循环创建行
for(int i=0;i<trList.size();i++){
HSSFRow row = sheet.createRow(i);
List<Element> tdList = trList.get(i).getChildren("td");
//该行td的序号
int tdIndex = 0;
for(int ii=0;ii<area[i].length;ii++){
row.createCell((short) ii);
HSSFCell cell = row.getCell((short) ii);
//判断是否为表头,使用对应的excel格式
if(i<headNum){
cell.setCellStyle(headStyle);
}else{
cell.setCellStyle(bodyStyle);
}
//如果对应的矩阵数字为1,则和横向前一单元格合并
if(area[i][ii]==1){
sheet.addMergedRegion(new Region(i,(short)(ii-1),i,(short)ii));
}else if(area[i][ii]==2){//如果对应的矩阵数字为2,则和纵向的前一单元格合并
sheet.addMergedRegion(new Region((i-1),(short)ii,i,(short)ii));

//sheet.addMergedRegion(new CellRangeAddress(i-1,i,ii,ii));
}else{//如果为0,显示td中对应的文字,td序号加1
cell.setCellValue(this.getInnerText(tdList.get(tdIndex)));
tdIndex ++;
}

}

}

wb.write(os);
is.close();
os.close();
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return url;
}

private static int[][] getCellArea(List<Element> trList){

a78b
//获取table单元格矩阵
System.out.println(trList.size());
System.out.println(trList.get(0));

Element headtr = trList.get(0);
List<Element> headTdList = headtr.getChildren("td");
//每行的未经合并的单元格个数
int cols = 0;
for(Element e:headTdList){
System.out.println("#"+e.getText());
int colspan = Integer.valueOf(null==e.getAttributeValue("colspan")?"0":e.getAttributeValue("colspan"));
if(colspan==0){
colspan =1;
}
cols += colspan;
}
//初始化单元格矩阵
int[][] area = new int[trList.size()][cols];
for(int i=0;i<trList.size();i++){
Element tr = trList.get(i);
List<Element> tdList = tr.getChildren("td");

for(int ii=0,tdIndex=0;ii<cols;ii++){
//如果大于0,表明已经处理过,不需再处理
if(area[i][ii]>0){
continue;
}
Element td = tdList.get(tdIndex);
int colspan = Integer.valueOf(null==td.getAttributeValue("colspan")?"0":td.getAttributeValue("colspan"));
colspan = colspan>1?colspan:1;
//单元格需要被横向合并声明为1
for(int m=1;m<colspan;m++){
area[i][ii+m]=1;
}
int rowspan = Integer.valueOf(null==td.getAttributeValue("rowspan")?"0":td.getAttributeValue("rowspan"));
rowspan = rowspan>1?rowspan:1;
//单元格需要被纵向向合并声明为2
for(int m=1;m<rowspan;m++){
area[m+i][ii] = 2;
}
//列和行都有跨度的区域,把第一行,第一列外的区域置为2
if(colspan>1 && rowspan>1){
for(int j=1;j<rowspan;j++){
for(int k=1;k<colspan;k++){
area[i+j][ii+k]=2;
}
}
}
tdIndex ++;
}
}
return area;
}

/**-
* 设置表头样式
* @param wb
* @return
*/
private HSSFCellStyle createHeadStyle(HSSFWorkbook wb){
HSSFCellStyle style = wb.createCellStyle();
HSSFFont headerFont = wb.createFont();
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFont(headerFont);

style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderTop(CellStyle.BORDER_THIN);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
return style;
}

/**-
* 设置表单记录样式
* @param wb
* @return
*/
private HSSFCellStyle createBodyStyle(HSSFWorkbook wb){
HSSFCellStyle style = wb.createCellStyle();
HSSFFont headerFont = wb.createFont();
headerFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFont(headerFont);

style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderTop(CellStyle.BORDER_THIN);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
return style;
}

private String getInnerText(Element td){
String txt = "";
if(td.getText()==null || td.getText().equals("")){
if(null != td.getChildren()){
for(int i=0;i<td.getChildren().size();i++){
Element e = (Element)td.getChildren().get(i);
txt += getInnerText(e);
}
}
}else{
txt = td.getText();
}
return txt; }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: