excel转html

poi提供了excel转html的代码,但是吧,有好多问题。当有合并单元格时边框获取不到,单元格内的字体样式也转换不了,现在对poi提供的Tohtml.java做了一些修改,修复了这些问题,记录下,以备之后用到

/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
==================================================================== */
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRElt;



/**
 * This example shows how to display a spreadsheet in HTML using the classes for
 * spreadsheet display.
 *
 * @author Ken Arnold, Industrious Media LLC
 */
public class ToHtml {
    private final Workbook wb;
    private final Appendable output;
    private boolean completeHTML;
    private Formatter out;
    private boolean gotBounds;
    private int firstColumn;
    private int endColumn;
    private HtmlHelper helper;

    private static final String DEFAULTS_CLASS = "excelDefaults";
    private static final String COL_HEAD_CLASS = "colHeader";
    private static final String ROW_HEAD_CLASS = "rowHeader";
    private HashSet<String> cell_merged= new HashSet<String>();//String = (x,y)  
    private HashSet<String> cell_hasValue= new HashSet<String>();//String = (x,y)  
    private HashSet<String> cell_hidden = new HashSet<String>();//String=(x,y);  
    private Map<String,String> cell_merged_print= new HashMap<String,String>();//String1 = (x,y),String2=rowspan,colspan  
    private Map<String,String> cell_merged_style= new HashMap<String,String>();//String1 = (x,y),String2=rowspan,colspan  

    private static final Map<HorizontalAlignment, String> HALIGN = mapFor(
            HorizontalAlignment.LEFT, "left",
            HorizontalAlignment.CENTER, "center",
            HorizontalAlignment.RIGHT, "right",
            HorizontalAlignment.FILL, "left",
            HorizontalAlignment.JUSTIFY, "left",
            HorizontalAlignment.CENTER_SELECTION, "center",
            HorizontalAlignment.GENERAL,"left"
            );

    private static final Map<VerticalAlignment, String> VALIGN = mapFor(
            VerticalAlignment.BOTTOM, "bottom",
            VerticalAlignment.CENTER, "middle",
            VerticalAlignment.TOP, "top");

    private static final Map<BorderStyle, String> BORDER = mapFor(
            BorderStyle.DASH_DOT, "dashed 1pt",
            BorderStyle.DASH_DOT_DOT, "dashed 1pt",
            BorderStyle.DASHED, "dashed 1pt",
            BorderStyle.DOTTED, "dotted 1pt",
            BorderStyle.DOUBLE, "double 3pt",
            BorderStyle.HAIR, "solid 1px",
            BorderStyle.MEDIUM, "solid 2pt",
            BorderStyle.MEDIUM_DASH_DOT, "dashed 2pt",
            BorderStyle.MEDIUM_DASH_DOT_DOT, "dashed 2pt",
            BorderStyle.MEDIUM_DASHED, "dashed 2pt",
            BorderStyle.NONE, "none",
            BorderStyle.SLANTED_DASH_DOT, "dashed 2pt",
            BorderStyle.THICK, "solid 3pt",
            BorderStyle.THIN, "solid 1pt");

    @SuppressWarnings({"unchecked"})
    private static <K, V> Map<K, V> mapFor(Object... mapping) {
        Map<K, V> map = new HashMap<K, V>();
        for (int i = 0; i < mapping.length; i += 2) {
            map.put((K) mapping[i], (V) mapping[i + 1]);
        }
        return map;
    }

    /**
     * Creates a new converter to HTML for the given workbook.
     *
     * @param wb     The workbook.
     * @param output Where the HTML output will be written.
     *
     * @return An object for converting the workbook to HTML.
     */
    public static ToHtml create(Workbook wb, Appendable output) {
        return new ToHtml(wb, output);
    }

    /**
     * Creates a new converter to HTML for the given workbook.  If the path ends
     * with "<tt>.xlsx</tt>" an {@link XSSFWorkbook} will be used; otherwise
     * this will use an {@link HSSFWorkbook}.
     *
     * @param path   The file that has the workbook.
     * @param output Where the HTML output will be written.
     *
     * @return An object for converting the workbook to HTML.
     */
    public static ToHtml create(String path, Appendable output)
            throws IOException {
        return create(new FileInputStream(path), output);
    }

    /**
     * Creates a new converter to HTML for the given workbook.  This attempts to
     * detect whether the input is XML (so it should create an {@link
     * XSSFWorkbook} or not (so it should create an {@link HSSFWorkbook}).
     *
     * @param in     The input stream that has the workbook.
     * @param output Where the HTML output will be written.
     *
     * @return An object for converting the workbook to HTML.
     */
    public static ToHtml create(InputStream in, Appendable output)
            throws IOException {
        try {
            Workbook wb = WorkbookFactory.create(in);
            return create(wb, output);
        } catch (InvalidFormatException e){
            throw new IllegalArgumentException("Cannot create workbook from stream", e);
        }
    }

    private ToHtml(Workbook wb, Appendable output) {
        if (wb == null)
            throw new NullPointerException("wb");
        if (output == null)
            throw new NullPointerException("output");
        this.wb = wb;
        this.output = output;
        setupColorMap();
    }

    private void setupColorMap() {
        if (wb instanceof HSSFWorkbook)
            helper = new HSSFHtmlHelper((HSSFWorkbook) wb);
        else if (wb instanceof XSSFWorkbook)
            helper = new XSSFHtmlHelper();
        else
            throw new IllegalArgumentException(
                    "unknown workbook type: " + wb.getClass().getSimpleName());
    }

    /**
     * Run this class as a program
     *
     * @param args The command line arguments.
     *
     * @throws Exception Exception we don't recover from.
     */
    public static void main(String[] args) throws Exception {
//        if(args.length < 2){
//            System.err.println("usage: ToHtml inputWorkbook outputHtmlFile");
//            return;
//        }
        //!!以GBK输出  
        ToHtml toHtml = ToHtml.create("Z:/Projects/1. DFB/日常巡检/账单/2016/12/账单日常巡检20161202.xlsx", new PrintWriter(new File("D:\\out2.html"),"utf-8"));  
        toHtml.setCompleteHTML(false);  
        toHtml.printPage(); 

    }

    public void setCompleteHTML(boolean completeHTML) {
        this.completeHTML = completeHTML;
    }

    public void printPage() throws IOException {
        try {
            ensureOut();
            if (completeHTML) {
                out.format(
                        "<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>%n");
                out.format("<html>%n");
                out.format("<head>%n");
                out.format("</head>%n");
                out.format("<body>%n");
            }

            print();

            if (completeHTML) {
                out.format("</body>%n");
                out.format("</html>%n");
            }
        } finally {
            if (out != null)
                out.close();
            if (output instanceof Closeable) {
                Closeable closeable = (Closeable) output;
                closeable.close();
            }
        }
    }

    public void print() {
        printInlineStyle();
        printSheets();
    }

    private void printInlineStyle() {
        //out.format("<link href=\"excelStyle.css\" rel=\"stylesheet\" type=\"text/css\">%n");
        out.format("<style type=\"text/css\">%n");
        printStyles();
        out.format("</style>%n");
    }

    private void ensureOut() {
        if (out == null)
            out = new Formatter(output);
    }

    public void printStyles() {
        ensureOut();

        // First, copy the base css
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(
                    getClass().getResourceAsStream("excelStyle.css")));
            String line;
            while ((line = in.readLine()) != null) {
                out.format("%s%n", line);
            }
        } catch (IOException e) {
            throw new IllegalStateException("Reading standard css", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    //noinspection ThrowFromFinallyBlock
                    throw new IllegalStateException("Reading standard css", e);
                }
            }
        }
        
        //添加合并区域的样式
        
        for(CellRangeAddress addr :wb.getSheetAt(0).getMergedRegions()){  
            int rowspan = addr.getLastRow()-addr.getFirstRow()+1;  
            int colspan = addr.getLastColumn()-addr.getFirstColumn()+1;  
           
            //左上角单元格坐标
            int firstX=addr.getFirstColumn();
            int firstY=addr.getFirstRow();
            //右下角单元格坐标
            int lastX=addr.getLastColumn();
            int lasyY=addr.getLastRow();
            
            //获取第一个单元格
            CellStyle lt= wb.getSheetAt(0).getRow(firstY).getCell(firstX).getCellStyle();
            CellStyle rb=wb.getSheetAt(0).getRow(lasyY).getCell(lastX).getCellStyle();
            printStyle(lt,rb);
            
    		Formatter formatter = new Formatter();
    		formatter.format("style_%02x_%02x",lt.getIndex(),rb.getIndex());
            String value=formatter.toString();//fmt.format("style_%02x_%02x", lr.getIndex(),rb.getIndex());
            formatter.close();
            for(int x=addr.getFirstColumn();x<=addr.getLastColumn();x++)  
                for(int y=addr.getFirstRow();y<=addr.getLastRow();y++){  
                    cell_merged.add("("+x+","+y+")");   
                    if(x==addr.getFirstColumn()&&y==addr.getFirstRow())  
                    	cell_merged_style.put("("+x+","+y+")",value);  
                }  
        }  

        // now add css for each used style
        Set<Short> seen = new HashSet<Short>();
        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
            Sheet sheet = wb.getSheetAt(i);
            Iterator<Row> rows = sheet.rowIterator();
            while (rows.hasNext()) {
                Row row = rows.next();
                for (Cell cell : row) {
                    CellStyle style = cell.getCellStyle();
                   
                    if (!seen.contains(style.getIndex())) {
                        printStyle(style);
                        seen.add(style.getIndex());
                    }
                }
            }
        }
    }

    private void printStyle(CellStyle style) {
        out.format(".%s .%s {%n", DEFAULTS_CLASS, styleName(style));
        styleContents(style);
        out.format("}%n");
    }
    private void printStyle(CellStyle lt,CellStyle rb) {
    	out.format(".%s .%s {%n", DEFAULTS_CLASS, styleName(lt,rb));
    	styleContents(lt,rb);
    	out.format("}%n");
    }

    private void styleContents(CellStyle style) {
        styleOut("text-align", style.getAlignmentEnum(), HALIGN);
        styleOut("vertical-align", style.getVerticalAlignmentEnum(), VALIGN);
        fontStyle(style);
        borderStyles(style);
        helper.colorStyles(style, out);
    }
    private void styleContents(CellStyle lt,CellStyle rb) {
    	styleOut("text-align", lt.getAlignmentEnum(), HALIGN);
    	styleOut("vertical-align", lt.getVerticalAlignmentEnum(), VALIGN);
    	fontStyle(lt);
    	borderStyles(lt,rb);
    	helper.colorStyles(lt, out);
    }

    private void borderStyles(CellStyle style) {
        styleOut("border-left", style.getBorderLeftEnum(), BORDER);
        styleOut("border-right", style.getBorderRightEnum(), BORDER);
        styleOut("border-top", style.getBorderTopEnum(), BORDER);
        styleOut("border-bottom", style.getBorderBottomEnum(), BORDER);
    }
    private void borderStyles(CellStyle lt,CellStyle rb) {
    	styleOut("border-left", lt.getBorderLeftEnum(), BORDER);
    	styleOut("border-right", rb.getBorderRightEnum(), BORDER);
    	styleOut("border-top", lt.getBorderTopEnum(), BORDER);
    	styleOut("border-bottom", rb.getBorderBottomEnum(), BORDER);
    }

    private void fontStyle(CellStyle style) {
        Font font = wb.getFontAt(style.getFontIndex());

        if (font.getBold())
            out.format("  font-weight: bold;%n");
        if (font.getItalic())
            out.format("  font-style: italic;%n");

        int fontheight = font.getFontHeightInPoints();
        if (fontheight == 9) {
            //fix for stupid ol Windows
            fontheight = 10;
        }
        out.format("  font-size: %dpt;%n", fontheight);

        // Font color is handled with the other colors
    }

    private String styleName(CellStyle style) {
        if (style == null)
            style = wb.getCellStyleAt((short) 0);
        StringBuilder sb = new StringBuilder();
        Formatter fmt = new Formatter(sb);
        try {
            fmt.format("style_%02x", style.getIndex());
            return fmt.toString();
        } finally {
            fmt.close();
        }
    }
    
    /**
     * 区域设置
     * @param lr
     * @param rb
     * @return
     */
    private String styleName(CellStyle lr,CellStyle rb) {
    	StringBuilder sb = new StringBuilder();
    	Formatter fmt = new Formatter(sb);
    	try {
    		fmt.format("style_%02x_%02x", lr.getIndex(),rb.getIndex());
    		return fmt.toString();
    	} finally {
    		fmt.close();
    	}
    }
    
    /**
     * 区域获取
     * @param lr
     * @param rb
     * @return
     */
    private String styleName(CellStyle style,Cell cell) {
        String point = "("+cell.getAddress().getColumn()+","+cell.getAddress().getRow()+")";  
        if(cell_merged_style.containsKey(point)){  
            return cell_merged_style.get(point); 
        }else{
        	return styleName(style);
        }
    }

    private <K> void styleOut(String attr, K key, Map<K, String> mapping) {
        String value = mapping.get(key);
        if (value != null) {
            out.format("  %s: %s;%n", attr, value);
        }
    }

    private static CellType ultimateCellType(Cell c) {
        CellType type = c.getCellTypeEnum();
        if (type == CellType.FORMULA)
            type = c.getCachedFormulaResultTypeEnum();
        return type;
    }
    private boolean shouldPrint(Cell cell){  
        String point = "("+cell.getAddress().getColumn()+","+cell.getAddress().getRow()+")";  
        if(cell_merged.contains(point)){  
            //不是第一次渲染则不渲染  
            if(!cell_merged_print.containsKey(point)){  
                return false;  
            }else{  
                //cell.getSheet().autoSizeColumn(cell.getAddress().getColumn());  
            }  
                  
        }  
        return true;  
    }  
    /** 
     * 用于分组全并的单元格,与其中要打印的单元格 
     * */  
    private void saprateCells(Sheet sheet) {  
        for(CellRangeAddress addr :sheet.getMergedRegions()){  
             int rowspan = addr.getLastRow()-addr.getFirstRow()+1;  
             int colspan = addr.getLastColumn()-addr.getFirstColumn()+1;  
            for(int x=addr.getFirstColumn();x<=addr.getLastColumn();x++)  
                for(int y=addr.getFirstRow();y<=addr.getLastRow();y++){  
                    cell_merged.add("("+x+","+y+")");   
                    if(x==addr.getFirstColumn()&&y==addr.getFirstRow())  
                        cell_merged_print.put("("+x+","+y+")",rowspan+","+colspan);  
                }  
        }  
        //过滤隐藏的列  
        for(int i= firstColumn;i<endColumn;i++){  
            if(sheet.isColumnHidden(i))  
                for(int j = sheet.getFirstRowNum();j<=sheet.getLastRowNum();j++)  
                    cell_hidden.add("("+i+","+j+")");  
        }     
          
        //过滤有值的cell  
        Iterator<Row> iter = sheet.rowIterator();  
        while(iter.hasNext()){  
            Row row = iter.next();  
            for(int i = row.getFirstCellNum();i<row.getLastCellNum();i++){  
                Cell cell = row.getCell(i);  
                  
                if(cell ==null)  
                    continue;  
                CellAddress address = cell.getAddress();  
                cell_hasValue.add("("+address.getColumn()+","+address.getRow()+")");  
            }  
              
        }  
    }

    private void printSheets() {
        ensureOut();
        Sheet sheet = wb.getSheetAt(0);
        ensureColumnBounds(sheet);  
        saprateCells(sheet);  
        printSheet(sheet);
    }

    public void printSheet(Sheet sheet) {
        ensureOut();
        float width = 0f;  
        //计算表格长度  
        for(int i=firstColumn;i<endColumn;i++){  
            width+=sheet.getColumnWidthInPixels(i);  
        } 
        
        out.format("<div align=\"center\"><table class=%s style=\"word-break:break-all;width:"+width+"px\">%n", DEFAULTS_CLASS);
        printCols(sheet);
        printSheetContent(sheet);
        out.format("</table>%n</div>%n");  
    }

    private void printCols(Sheet sheet) {
        out.format("<col/>%n");
        ensureColumnBounds(sheet);
        for (int i = firstColumn; i < endColumn; i++) {
            out.format("<col/>%n");
        }
    }

    private void ensureColumnBounds(Sheet sheet) {
        if (gotBounds)
            return;

        Iterator<Row> iter = sheet.rowIterator();
        firstColumn = (iter.hasNext() ? Integer.MAX_VALUE : 0);
        endColumn = 0;
        while (iter.hasNext()) {
            Row row = iter.next();
            short firstCell = row.getFirstCellNum();
            if (firstCell >= 0) {
                firstColumn = Math.min(firstColumn, firstCell);
                endColumn = Math.max(endColumn, row.getLastCellNum());
            }
        }
        gotBounds = true;
    }

    private void printColumnHeads() {
        out.format("<thead>%n");
        out.format("  <tr class=%s>%n", COL_HEAD_CLASS);
        out.format("    <th class=%s>◊</th>%n", COL_HEAD_CLASS);
        //noinspection UnusedDeclaration
        StringBuilder colName = new StringBuilder();
        for (int i = firstColumn; i < endColumn; i++) {
            colName.setLength(0);
            int cnum = i;
            do {
                colName.insert(0, (char) ('A' + cnum % 26));
                cnum /= 26;
            } while (cnum > 0);
            out.format("    <th class=%s>%s</th>%n", COL_HEAD_CLASS, colName);
        }
        out.format("  </tr>%n");
        out.format("</thead>%n");
    }
    /**
     * 转换富文本样式
     * @param font
     * @return
     */
    private String fontStyleDetail(Font font){  
        StringBuffer buf = new StringBuffer("");  
        XSSFFont font1 = (XSSFFont)font;  
        if(!(font1.getXSSFColor()==null||font1.getXSSFColor().isAuto()))  
            buf.append("color:#"+font1.getXSSFColor().getARGBHex().substring(2)+";");  
         if (font.getBold()){  
             buf.append("font-weight: bold;");  
         }else{  
             buf.append("font-weight: normal;");  
         }       
         if(font.getItalic())  
             buf.append("font-style:italic;");  
         buf.append("font-family:"+font.getFontName()+";");  
         buf.append("font-size:"+font.getFontHeightInPoints()+"pt;");  
         return buf.toString();  
    } 
    /**
     * 把单元格转换成htmlcode
     * @param cell
     * @return
     */
    private String abtainHtmlContent(Cell cell){
    	//cell.getStringCellValue();
		XSSFRichTextString richText = (XSSFRichTextString) cell.getRichStringCellValue();
		CTRElt[] ctrs = richText.getCTRst().getRArray();
		if(ctrs.length>0){
			StringBuffer htmlcode=new StringBuffer();
			int startIndex = 0;  
   			for (CTRElt ctrElt : ctrs) {
       			
       		  XSSFFont font =richText.getFontAtIndex(startIndex);  
              startIndex += ctrElt.getT().length();  
              htmlcode.append("<font style=\""+fontStyleDetail(font)+" \">"+ctrElt.getT()+"</font>") ;  
			}
   			
   			return htmlcode.toString();
		}else{
			return cell.getStringCellValue();
		}
    }

    /**
     * 转换表单
     * @param sheet
     */
    private void printSheetContent(Sheet sheet) {
    	//是否打印列头行头
       // printColumnHeads();

        out.format("<tbody>%n");
        Iterator<Row> rows = sheet.rowIterator();
        //Iterator<Row> rows = sheet.rowIterator();  
        for(int num=sheet.getFirstRowNum();num<=sheet.getLastRowNum();num++) {  
            Row row = sheet.getRow(num);  
            if(row==null){  
                out.format("<tr><td >  </td></tr>%n");  
                continue;  
            }  
            if(row.getZeroHeight())  
                continue;  

            out.format("  <tr>%n");
            //是否打印行头 行号
           // out.format("    <td class=%s>%d</td>%n", ROW_HEAD_CLASS, row.getRowNum() + 1);
            for (int i = firstColumn; i < endColumn; i++) {
                String content = " ";
                String attrs = "";
                CellStyle style = null;
                String point = "("+i+","+num+")";  
                if(cell_hidden.contains(point))  
                    continue;  
                if(!cell_hasValue.contains(point)){  
                     out.format("    <td class=%s %s>%s</td>%n", styleName(style),  
                             attrs, content);  
                     continue;  
                }  
                if (i >= row.getFirstCellNum() && i < row.getLastCellNum()) {
                    Cell cell = row.getCell(i);
                    if (shouldPrint(cell)) {
                    	
                        style = cell.getCellStyle();
                        attrs = tagStyle(cell, style);
                        //Set the value that is rendered for the cell
                        //also applies the format
                    	switch(cell.getCellTypeEnum()){
                    	case STRING:
                    		content = abtainHtmlContent(cell);
                    		break;
                    	case BLANK:
                    		content="";
                    		break;
                    	case BOOLEAN:
                    		break;
                    	case ERROR:
                    		break;
                    	case FORMULA:
                    		break;
                    	case NUMERIC:
                    	    short format = cell.getCellStyle().getDataFormat();  
                    	    SimpleDateFormat sdf = null;  
                    	    if(format == 14 || format == 31 || format == 57 || format == 58){  
                    	        //日期  
                    	        sdf = new SimpleDateFormat("yyyy-MM-dd");  
                        	    double value = cell.getNumericCellValue();  
                        	    Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);  
                        	    if(date!=null){
                        	    	content = sdf.format(date);                     		
                        	    }
                    	    }else if (format == 20 || format == 32) {  
                    	        //时间  
                    	        sdf = new SimpleDateFormat("HH:mm");  
                        	    double value = cell.getNumericCellValue();  
                        	    Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);  
                        	    if(date!=null){
                        	    	content = sdf.format(date);                     		
                        	    }
                    	    }else if(format == 176){
                    	        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
                        	    double value = cell.getNumericCellValue();  
                        	    Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);  
                        	    if(date!=null){
                        	    	content = sdf.format(date);                     		
                        	    }
                    	    }else{
                                double value = cell.getNumericCellValue();  
                                DecimalFormat format2 = new DecimalFormat();  
                                String temp = cell.getCellStyle().getDataFormatString();  
                                // 单元格设置成常规  
                                if (temp.equals("General")) {  
                                    format2.applyPattern("#");  
                                }  
                                content = format2.format(value); 
                    	    }

                            break;
                    	default:
                    			
                    		
                    	}
                    	
                    	content=content.replaceAll("\n", "<br/>");
                    	out.format("    <td class=%s %s>%s</td>%n", styleName(style,cell),attrs, content);
                    }
                    
                }
            }
            out.format("  </tr>%n");
        }
        out.format("</tbody>%n");
    }

    /**
     * 合并单元格式 设置rowspan colspan
     * @param cell
     * @param style
     * @return
     */
    private String tagStyle(Cell cell, CellStyle style) {
        //调整align  
        StringBuffer buf = new StringBuffer("style=\"");  
        //调整宽度  
       // String width = cell.getSheet().getColumnWidthInPixels(cell.getColumnIndex())+"px;";  
        Font font = wb.getFontAt(style.getFontIndex());  
        String width = cell.getSheet().getColumnWidth(cell.getColumnIndex())/256*font.getFontHeight()/20+"pt";//通过字体大小计算Cell宽度  
        buf.append("width:"+width);  
        buf.append("\" ");  
        String point = "("+cell.getAddress().getColumn()+","+cell.getAddress().getRow()+")";  
        if(cell_merged_print.containsKey(point)){  
            String[] str = cell_merged_print.get(point).split(",");  
            int rowspan =Integer.parseInt(str[0]);  
            int colspan =Integer.parseInt(str[1]);  
            if(rowspan>1)buf.append("rowspan=\""+rowspan+"\" ");  
            if(colspan>1)buf.append("colspan=\""+colspan+"\" ");  
        }  
         
        return buf.toString(); 
    }
}

测试方法

	@Test
	public void generatorHtml() throws FileNotFoundException, UnsupportedEncodingException, IOException{
		System.out.println("generatorHtml................");
		String excelPath="E:/e.xlsx";
		String htmlPath="E:/bc.html";
		ExcelUtil.excelToHtml(excelPath, htmlPath, "gbk", false);
        ToHtml toHtml = ToHtml.create(excelPath, new PrintWriter(new File(htmlPath),"gbk"));  
        toHtml.setCompleteHTML(isCompleteHTML);  
        toHtml.printPage(); 
               System.out.println("generatorHtml end................");
	}

所需要的jar的pom文件,

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.16-beta1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-excelant</artifactId>
			<version>3.16-beta1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-scratchpad</artifactId>
			<version>3.16-beta1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.16-beta1</version>
		</dependency>
		<dependency>  
		    <groupId>org.apache.poi</groupId>  
		    <artifactId>ooxml-schemas</artifactId>  
		    <version>1.3</version>  
		</dependency> 


其它所需要的文件可以从poi官网上下载,也可以从下面的地址上获取

http://download.csdn.net/detail/riapgypm/9724715

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值