• Excel在线预览(通过poi转html,含里面的图片)


    支持03和07excel转html,直接上代码

    测试类

     1 /**
     2  * 主方法
     3  * @author asus
     4  *
     5  */
     6 public class App2 {
     7     
     8     public static void main(String[] args) {
     9         
    10             ExcelToHtml.excelToHtml("C:\Users\asus\Desktop\xxx.xlsx", "E:/test.html");
    11         
    12     }
    13 }

    主类

      1 package com.topcheer.html;
      2 
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.FileOutputStream;
      6 import java.io.IOException;
      7 import java.io.InputStream;
      8 import java.io.PrintStream;
      9 import java.text.DecimalFormat;
     10 import java.text.SimpleDateFormat;
     11 import java.util.Date;
     12 import java.util.HashMap;
     13 import java.util.List;
     14 import java.util.Map;
     15 
     16 import org.apache.poi.POIXMLDocumentPart;
     17 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
     18 import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
     19 import org.apache.poi.hssf.usermodel.HSSFDataFormat;
     20 import org.apache.poi.hssf.usermodel.HSSFDateUtil;
     21 import org.apache.poi.hssf.usermodel.HSSFFont;
     22 import org.apache.poi.hssf.usermodel.HSSFPalette;
     23 import org.apache.poi.hssf.usermodel.HSSFPicture;
     24 import org.apache.poi.hssf.usermodel.HSSFPictureData;
     25 import org.apache.poi.hssf.usermodel.HSSFShape;
     26 import org.apache.poi.hssf.usermodel.HSSFSheet;
     27 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
     28 import org.apache.poi.hssf.util.HSSFColor;
     29 import org.apache.poi.ss.usermodel.Cell;
     30 import org.apache.poi.ss.usermodel.CellStyle;
     31 import org.apache.poi.ss.usermodel.PictureData;
     32 import org.apache.poi.ss.usermodel.Row;
     33 import org.apache.poi.ss.usermodel.Sheet;
     34 import org.apache.poi.ss.usermodel.Workbook;
     35 import org.apache.poi.ss.usermodel.WorkbookFactory;
     36 import org.apache.poi.ss.util.CellRangeAddress;
     37 import org.apache.poi.xssf.usermodel.XSSFCellStyle;
     38 import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
     39 import org.apache.poi.xssf.usermodel.XSSFColor;
     40 import org.apache.poi.xssf.usermodel.XSSFDrawing;
     41 import org.apache.poi.xssf.usermodel.XSSFFont;
     42 import org.apache.poi.xssf.usermodel.XSSFPicture;
     43 import org.apache.poi.xssf.usermodel.XSSFShape;
     44 import org.apache.poi.xssf.usermodel.XSSFSheet;
     45 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
     46 import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
     47 /**
     48  * Excel转html
     49  *
     50  */
     51 public class ExcelToHtml {
     52     
     53        private static String UPLOAD_FILE="E:/";
     54 
     55 
     56      /**
     57      * 测试
     58      * 
     59      * @param args
     60      */
     61     public static void excelToHtml(String path,String htmlPositon) {
     62         InputStream is = null;
     63         String htmlExcel = null;
     64         String[] str = path.split("/");
     65         String fileName = str[str.length-1];
     66         try {
     67             File sourcefile = new File(path);
     68             is = new FileInputStream(sourcefile);
     69             Workbook wb = WorkbookFactory.create(is);// 此WorkbookFactory在POI-3.10版本中使用需要添加dom4j
     70             if (wb instanceof XSSFWorkbook) {
     71                 XSSFWorkbook xWb = (XSSFWorkbook) wb;
     72                 htmlExcel = ExcelToHtml.getExcelInfo(xWb, true);
     73             } else if (wb instanceof HSSFWorkbook) {
     74                 HSSFWorkbook hWb = (HSSFWorkbook) wb;
     75                 htmlExcel = ExcelToHtml.getExcelInfo(hWb, true);
     76             }
     77             writeFile(htmlExcel,htmlPositon,fileName);
     78         } catch (Exception e) {
     79             e.printStackTrace();
     80         } finally {
     81             try {
     82                 is.close();
     83             } catch (IOException e) {
     84                 e.printStackTrace();
     85             }
     86         }
     87     }
     88     
     89     @SuppressWarnings("resource")
     90     private static void writeFile(String content,String htmlPath, String fileName){
     91         File file2 = new File(htmlPath);
     92         StringBuilder sb = new StringBuilder();
     93         try {
     94             file2.createNewFile();//创建文件
     95  
     96             sb.append("<html><head><meta http-equiv="Content-Type" charset="utf-8"><title>"+fileName+"</title></head><body>");
     97             sb.append("<div>");
     98             sb.append(content);
     99             sb.append("</div>");
    100             sb.append("</body></html>");
    101  
    102             PrintStream printStream = new PrintStream(new FileOutputStream(file2));
    103  
    104             printStream.println(sb.toString());//将字符串写入文件
    105  
    106         } catch (IOException e) {
    107  
    108             e.printStackTrace();
    109         }
    110  
    111     }
    112 
    113 
    114     /**
    115      * 程序入口方法
    116      * 
    117      * @param filePath
    118      *            文件的路径
    119      * @param isWithStyle
    120      *            是否需要表格样式 包含 字体 颜色 边框 对齐方式
    121      * @return
    122      *         <table>
    123      *         ...
    124      *         </table>
    125      *         字符串
    126      */
    127     public String readExcelToHtml(String filePath, boolean isWithStyle) {
    128 
    129         InputStream is = null;
    130         String htmlExcel = null;
    131         try {
    132             File sourcefile = new File(filePath);
    133             is = new FileInputStream(sourcefile);
    134             Workbook wb = WorkbookFactory.create(is);
    135             if (wb instanceof XSSFWorkbook) {
    136                 XSSFWorkbook xWb = (XSSFWorkbook) wb;
    137                 htmlExcel = ExcelToHtml.getExcelInfo(xWb, isWithStyle);
    138             } else if (wb instanceof HSSFWorkbook) {
    139                 HSSFWorkbook hWb = (HSSFWorkbook) wb;
    140                 htmlExcel = ExcelToHtml.getExcelInfo(hWb, isWithStyle);
    141             }
    142         } catch (Exception e) {
    143             e.printStackTrace();
    144         } finally {
    145             try {
    146                 is.close();
    147             } catch (IOException e) {
    148                 e.printStackTrace();
    149             }
    150         }
    151         return htmlExcel;
    152     }
    153 
    154     public static String getExcelInfo(Workbook wb, boolean isWithStyle) {
    155 
    156         StringBuffer sb = new StringBuffer();
    157         for(int i=0;i<wb.getNumberOfSheets();i++) {
    158               Sheet sheet = wb.getSheetAt(i);// 获取第一个Sheet的内容
    159               String sheetName = sheet.getSheetName();
    160               int lastRowNum = sheet.getLastRowNum();
    161               Map<String, String> map[] = getRowSpanColSpanMap(sheet);
    162               sb.append("<h3>"+sheetName+"</h3>");
    163               sb.append("<table style='border-collapse:collapse;' width='100%'>");
    164            // map等待存储excel图片
    165               Map<String, PictureData> sheetIndexPicMap = getSheetPictrues(i, sheet, wb);
    166               Map<String, String> imgMap = new HashMap<String, String>();
    167               if (sheetIndexPicMap != null) {
    168                   imgMap = printImg(sheetIndexPicMap);
    169                   printImpToWb(imgMap, wb);
    170               }
    171               Row row = null; // 兼容
    172               Cell cell = null; // 兼容
    173               for (int rowNum = sheet.getFirstRowNum(); rowNum <= lastRowNum; rowNum++) {
    174                   row = sheet.getRow(rowNum);
    175                   if (row == null) {
    176                       sb.append("<tr><td > &nbsp;</td></tr>");
    177                       continue;
    178                   }
    179                   sb.append("<tr>");
    180                   int lastColNum = row.getLastCellNum();
    181                   for (int colNum = 0; colNum < lastColNum; colNum++) {
    182                       cell = row.getCell(colNum);
    183                       if (cell == null) { // 特殊情况 空白的单元格会返回null
    184                           sb.append("<td>&nbsp;</td>");
    185                           continue;
    186                       }
    187                       String imageHtml = "";
    188                       String imageRowNum = i + "_" + rowNum + "_" + colNum;
    189                       if (sheetIndexPicMap != null && sheetIndexPicMap.containsKey(imageRowNum)) {
    190                           String imagePath = imgMap.get(imageRowNum);
    191                           imageHtml = "<img src='" + imagePath + "' style='height:auto;'>";
    192                       }
    193                       String stringValue = getCellValue(cell);
    194                       if (map[0].containsKey(rowNum + "," + colNum)) {
    195                           String pointString = map[0].get(rowNum + "," + colNum);
    196                           map[0].remove(rowNum + "," + colNum);
    197                           int bottomeRow = Integer.valueOf(pointString.split(",")[0]);
    198                           int bottomeCol = Integer.valueOf(pointString.split(",")[1]);
    199                           int rowSpan = bottomeRow - rowNum + 1;
    200                           int colSpan = bottomeCol - colNum + 1;
    201                           sb.append("<td rowspan= '" + rowSpan + "' colspan= '" + colSpan + "' ");
    202                       } else if (map[1].containsKey(rowNum + "," + colNum)) {
    203                           map[1].remove(rowNum + "," + colNum);
    204                           continue;
    205                       } else {
    206                           sb.append("<td ");
    207                       }
    208                       // 判断是否需要样式
    209                       if (isWithStyle) {
    210                           dealExcelStyle(wb, sheet, cell, sb);// 处理单元格样式
    211                       }
    212                       sb.append(">");
    213                       if (sheetIndexPicMap != null && sheetIndexPicMap.containsKey(imageRowNum)) {
    214                           sb.append(imageHtml);
    215                       }
    216                       if (stringValue == null || "".equals(stringValue.trim())) {
    217                           sb.append(" &nbsp; ");
    218                       } else {
    219                           // 将ascii码为160的空格转换为html下的空格(&nbsp;)
    220                           sb.append(stringValue.replace(String.valueOf((char) 160), "&nbsp;"));
    221                       }
    222                       sb.append("</td>");
    223                   }
    224                   sb.append("</tr>");
    225               }
    226 
    227               sb.append("</table>");
    228         }
    229         
    230       
    231         return sb.toString();
    232     }
    233     
    234     /**
    235      * 获取Excel图片公共方法
    236      *
    237      * @param sheetNum 当前sheet编号
    238      * @param sheet    当前sheet对象
    239      * @param workbook 工作簿对象
    240      * @return Map key:图片单元格索引(0_1_1)String,value:图片流PictureData
    241      */
    242     public static Map<String, PictureData> getSheetPictrues(int sheetNum, Sheet sheet, Workbook workbook) {
    243         if (workbook instanceof HSSFWorkbook) {
    244             return getSheetPictrues03(sheetNum, (HSSFSheet) sheet, (HSSFWorkbook) workbook);
    245         } else if (workbook instanceof XSSFWorkbook) {
    246             return getSheetPictrues07(sheetNum, (XSSFSheet) sheet, (XSSFWorkbook) workbook);
    247         } else {
    248             return null;
    249         }
    250     }
    251 
    252     /**
    253      * 获取Excel2003图片
    254      *
    255      * @param sheetNum 当前sheet编号
    256      * @param sheet    当前sheet对象
    257      * @param workbook 工作簿对象
    258      * @return Map key:图片单元格索引(0_1_1)String,value:图片流PictureData
    259      * @throws IOException
    260      */
    261     private static Map<String, PictureData> getSheetPictrues03(int sheetNum,
    262                                                                HSSFSheet sheet, HSSFWorkbook workbook) {
    263         Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
    264         List<HSSFPictureData> pictures = workbook.getAllPictures();
    265         if (pictures.size() != 0) {
    266             for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {
    267                 HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
    268                 shape.getLineWidth();
    269                 if (shape instanceof HSSFPicture) {
    270                     HSSFPicture pic = (HSSFPicture) shape;
    271                     int pictureIndex = pic.getPictureIndex() - 1;
    272                     HSSFPictureData picData = pictures.get(pictureIndex);
    273                     String picIndex = String.valueOf(sheetNum) + "_"
    274                             + String.valueOf(anchor.getRow1()) + "_"
    275                             + String.valueOf(anchor.getCol1());
    276                     sheetIndexPicMap.put(picIndex, picData);
    277                 }
    278             }
    279             return sheetIndexPicMap;
    280         } else {
    281             return null;
    282         }
    283     }
    284 
    285     /**
    286      * 获取Excel2007图片
    287      *
    288      * @param sheetNum 当前sheet编号
    289      * @param sheet    当前sheet对象
    290      * @param workbook 工作簿对象
    291      * @return Map key:图片单元格索引(0_1_1)String,value:图片流PictureData
    292      */
    293     private static Map<String, PictureData> getSheetPictrues07(int sheetNum,
    294                                                                XSSFSheet sheet, XSSFWorkbook workbook) {
    295         Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
    296         for (POIXMLDocumentPart dr : sheet.getRelations()) {
    297             if (dr instanceof XSSFDrawing) {
    298                 XSSFDrawing drawing = (XSSFDrawing) dr;
    299                 List<XSSFShape> shapes = drawing.getShapes();
    300                 for (XSSFShape shape : shapes) {
    301                     XSSFPicture pic = (XSSFPicture) shape;
    302                     XSSFClientAnchor anchor = pic.getPreferredSize();
    303                     CTMarker ctMarker = anchor.getFrom();
    304                     String picIndex = String.valueOf(sheetNum) + "_"
    305                             + ctMarker.getRow() + "_"
    306                             + ctMarker.getCol();
    307                     sheetIndexPicMap.put(picIndex, pic.getPictureData());
    308                 }
    309             }
    310         }
    311         return sheetIndexPicMap;
    312     }
    313     
    314     /**
    315      * 对图片单元格赋值使其可读取到
    316      * <p>add by CJ 2018年5月21日</p>
    317      *
    318      * @param imgMap
    319      * @param wb
    320      */
    321     @SuppressWarnings("unused")
    322     private static void printImpToWb(Map<String, String> imgMap, Workbook wb) {
    323         Sheet sheet = null;
    324         Row row = null;
    325         String[] sheetRowCol = new String[3];
    326         for (String key : imgMap.keySet()) {
    327             sheetRowCol = key.split("_");
    328             sheet = wb.getSheetAt(Integer.parseInt(sheetRowCol[0]));
    329             row = sheet.getRow(Integer.parseInt(sheetRowCol[1])) == null ? sheet.createRow(Integer.parseInt(sheetRowCol[1])) :
    330                     sheet.getRow(Integer.parseInt(sheetRowCol[1]));
    331             Cell cell = row.getCell(Integer.parseInt(sheetRowCol[2])) == null ? row.createCell(Integer.parseInt(sheetRowCol[2])) :
    332                     row.getCell(Integer.parseInt(sheetRowCol[2]));
    333         }
    334     }
    335 
    336 
    337     public static Map<String, String> printImg(Map<String, PictureData> map) {
    338         Map<String, String> imgMap = new HashMap<String, String>();
    339         String imgName = null;
    340         try {
    341             Object key[] = map.keySet().toArray();
    342             for (int i = 0; i < map.size(); i++) {
    343                 // 获取图片流
    344                 PictureData pic = map.get(key[i]);
    345                 // 获取图片索引
    346                 String picName = key[i].toString();
    347                 // 获取图片格式
    348                 String ext = pic.suggestFileExtension();
    349                 byte[] data = pic.getData();
    350                 File uploadFile = new File(UPLOAD_FILE);
    351                 if (!uploadFile.exists()) {
    352                     uploadFile.mkdirs();
    353                 }
    354                 imgName = picName + "_" + new Date().getTime() + "." + ext;
    355                 FileOutputStream out = new FileOutputStream(UPLOAD_FILE + imgName);
    356                 imgMap.put(picName, UPLOAD_FILE + imgName);
    357                 out.write(data);
    358                 out.flush();
    359                 out.close();
    360             }
    361         } catch (Exception e) {
    362         }
    363         return imgMap;
    364     }
    365     
    366     @SuppressWarnings("unchecked")
    367     private static Map<String, String>[] getRowSpanColSpanMap(Sheet sheet) {
    368         Map<String, String> map0 = new HashMap<String, String>();
    369         Map<String, String> map1 = new HashMap<String, String>();
    370         int mergedNum = sheet.getNumMergedRegions();
    371         CellRangeAddress range = null;
    372         for (int i = 0; i < mergedNum; i++) {
    373             range = sheet.getMergedRegion(i);
    374             int topRow = range.getFirstRow();
    375             int topCol = range.getFirstColumn();
    376             int bottomRow = range.getLastRow();
    377             int bottomCol = range.getLastColumn();
    378             map0.put(topRow + "," + topCol, bottomRow + "," + bottomCol);
    379             // System.out.println(topRow + "," + topCol + "," + bottomRow + ","
    380             // + bottomCol);
    381             int tempRow = topRow;
    382             while (tempRow <= bottomRow) {
    383                 int tempCol = topCol;
    384                 while (tempCol <= bottomCol) {
    385                     map1.put(tempRow + "," + tempCol, "");
    386                     tempCol++;
    387                 }
    388                 tempRow++;
    389             }
    390             map1.remove(topRow + "," + topCol);
    391         }
    392         
    393         @SuppressWarnings("rawtypes")
    394         Map[] map = { map0, map1 };
    395         return map;
    396     }
    397 
    398     /**
    399      * 获取表格单元格Cell内容
    400      * 
    401      * @param cell
    402      * @return
    403      */
    404     private static String getCellValue(Cell cell) {
    405         String result = new String();
    406         switch (cell.getCellType()) {
    407         case Cell.CELL_TYPE_NUMERIC:// 数字类型
    408             if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
    409                 SimpleDateFormat sdf = null;
    410                 if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
    411                     sdf = new SimpleDateFormat("HH:mm");
    412                 } else {// 日期
    413                     sdf = new SimpleDateFormat("yyyy-MM-dd");
    414                 }
    415                 Date date = cell.getDateCellValue();
    416                 result = sdf.format(date);
    417             } else if (cell.getCellStyle().getDataFormat() == 58) {
    418                 // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
    419                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    420                 double value = cell.getNumericCellValue();
    421                 Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
    422                 result = sdf.format(date);
    423             } else {
    424                 double value = cell.getNumericCellValue();
    425                 CellStyle style = cell.getCellStyle();
    426                 DecimalFormat format = new DecimalFormat();
    427                 String temp = style.getDataFormatString();
    428                 // 单元格设置成常规
    429                 if (temp.equals("General")) {
    430                     format.applyPattern("#");
    431                 }
    432                 result = format.format(value);
    433             }
    434             break;
    435         case Cell.CELL_TYPE_STRING:// String类型
    436             result = cell.getRichStringCellValue().toString();
    437             break;
    438         case Cell.CELL_TYPE_BLANK:
    439             result = "";
    440             break;
    441         default:
    442             result = "";
    443             break;
    444         }
    445         return result;
    446     }
    447 
    448     /**
    449      * 处理表格样式
    450      * 
    451      * @param wb
    452      * @param sheet
    453      * @param cell
    454      * @param sb
    455      */
    456     private static void dealExcelStyle(Workbook wb, Sheet sheet, Cell cell, StringBuffer sb) {
    457 
    458         CellStyle cellStyle = cell.getCellStyle();
    459         if (cellStyle != null) {
    460             short alignment = cellStyle.getAlignment();
    461             sb.append("align='" + convertAlignToHtml(alignment) + "' ");// 单元格内容的水平对齐方式
    462             short verticalAlignment = cellStyle.getVerticalAlignment();
    463             sb.append("valign='" + convertVerticalAlignToHtml(verticalAlignment) + "' ");// 单元格中内容的垂直排列方式
    464             if (wb instanceof XSSFWorkbook) {
    465                 XSSFFont xf = ((XSSFCellStyle) cellStyle).getFont();
    466                 short boldWeight = xf.getBoldweight();
    467                 sb.append("style='");
    468                 sb.append("font-weight:" + boldWeight + ";"); // 字体加粗
    469                 sb.append("font-size: " + xf.getFontHeight() / 2 + "%;"); // 字体大小
    470                 int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
    471                 sb.append("" + columnWidth + "px;");
    472                 XSSFColor xc = xf.getXSSFColor();
    473                 if (xc != null && !"".equals(xc)) {
    474                     String string = xc.getARGBHex();
    475                     if(string!=null&& !"".equals(string)) {
    476                         sb.append("color:#" + string.substring(2) + ";"); // 字体颜色
    477                     }
    478                 }
    479 
    480                 XSSFColor bgColor = (XSSFColor) cellStyle.getFillForegroundColorColor();
    481                 if (bgColor != null && !"".equals(bgColor) && bgColor!=null) {
    482                     String argbHex = bgColor.getARGBHex();
    483                     if(argbHex!=null && !"".equals(argbHex)) {
    484                         sb.append("background-color:#" + argbHex.substring(2) + ";"); // 背景颜色
    485                     }
    486                 }
    487                 sb.append(getBorderStyle(0, cellStyle.getBorderTop(),
    488                         ((XSSFCellStyle) cellStyle).getTopBorderXSSFColor()));
    489                 sb.append(getBorderStyle(1, cellStyle.getBorderRight(),
    490                         ((XSSFCellStyle) cellStyle).getRightBorderXSSFColor()));
    491                 sb.append(getBorderStyle(2, cellStyle.getBorderBottom(),
    492                         ((XSSFCellStyle) cellStyle).getBottomBorderXSSFColor()));
    493                 sb.append(getBorderStyle(3, cellStyle.getBorderLeft(),
    494                         ((XSSFCellStyle) cellStyle).getLeftBorderXSSFColor()));
    495 
    496             } else if (wb instanceof HSSFWorkbook) {
    497 
    498                 HSSFFont hf = ((HSSFCellStyle) cellStyle).getFont(wb);
    499                 short boldWeight = hf.getBoldweight();
    500                 short fontColor = hf.getColor();
    501                 sb.append("style='");
    502                 HSSFPalette palette = ((HSSFWorkbook) wb).getCustomPalette(); // 类HSSFPalette用于求的颜色的国际标准形式
    503                 HSSFColor hc = palette.getColor(fontColor);
    504                 sb.append("font-weight:" + boldWeight + ";"); // 字体加粗
    505                 sb.append("font-size: " + hf.getFontHeight() / 2 + "%;"); // 字体大小
    506                 String fontColorStr = convertToStardColor(hc);
    507                 if (fontColorStr != null && !"".equals(fontColorStr.trim())) {
    508                     sb.append("color:" + fontColorStr + ";"); // 字体颜色
    509                 }
    510                 int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
    511                 sb.append("" + columnWidth + "px;");
    512                 short bgColor = cellStyle.getFillForegroundColor();
    513                 hc = palette.getColor(bgColor);
    514                 String bgColorStr = convertToStardColor(hc);
    515                 if (bgColorStr != null && !"".equals(bgColorStr.trim())) {
    516                     sb.append("background-color:" + bgColorStr + ";"); // 背景颜色
    517                 }
    518                 sb.append(getBorderStyle(palette, 0, cellStyle.getBorderTop(), cellStyle.getTopBorderColor()));
    519                 sb.append(getBorderStyle(palette, 1, cellStyle.getBorderRight(), cellStyle.getRightBorderColor()));
    520                 sb.append(getBorderStyle(palette, 3, cellStyle.getBorderLeft(), cellStyle.getLeftBorderColor()));
    521                 sb.append(getBorderStyle(palette, 2, cellStyle.getBorderBottom(), cellStyle.getBottomBorderColor()));
    522             }
    523 
    524             sb.append("' ");
    525         }
    526     }
    527 
    528     /**
    529      * 单元格内容的水平对齐方式
    530      * 
    531      * @param alignment
    532      * @return
    533      */
    534     private static String convertAlignToHtml(short alignment) {
    535 
    536         String align = "left";
    537         switch (alignment) {
    538         case CellStyle.ALIGN_LEFT:
    539             align = "left";
    540             break;
    541         case CellStyle.ALIGN_CENTER:
    542             align = "center";
    543             break;
    544         case CellStyle.ALIGN_RIGHT:
    545             align = "right";
    546             break;
    547         default:
    548             break;
    549         }
    550         return align;
    551     }
    552 
    553     /**
    554      * 单元格中内容的垂直排列方式
    555      * 
    556      * @param verticalAlignment
    557      * @return
    558      */
    559     private static String convertVerticalAlignToHtml(short verticalAlignment) {
    560 
    561         String valign = "middle";
    562         switch (verticalAlignment) {
    563         case CellStyle.VERTICAL_BOTTOM:
    564             valign = "bottom";
    565             break;
    566         case CellStyle.VERTICAL_CENTER:
    567             valign = "center";
    568             break;
    569         case CellStyle.VERTICAL_TOP:
    570             valign = "top";
    571             break;
    572         default:
    573             break;
    574         }
    575         return valign;
    576     }
    577 
    578     private static String convertToStardColor(HSSFColor hc) {
    579 
    580         StringBuffer sb = new StringBuffer("");
    581         if (hc != null) {
    582             if (HSSFColor.AUTOMATIC.index == hc.getIndex()) {
    583                 return null;
    584             }
    585             sb.append("#");
    586             for (int i = 0; i < hc.getTriplet().length; i++) {
    587                 sb.append(fillWithZero(Integer.toHexString(hc.getTriplet()[i])));
    588             }
    589         }
    590 
    591         return sb.toString();
    592     }
    593 
    594     private static String fillWithZero(String str) {
    595         if (str != null && str.length() < 2) {
    596             return "0" + str;
    597         }
    598         return str;
    599     }
    600 
    601     static String[] bordesr = { "border-top:", "border-right:", "border-bottom:", "border-left:" };
    602     static String[] borderStyles = { "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ",
    603             "solid ", "solid", "solid", "solid", "solid", "solid" };
    604 
    605     private static String getBorderStyle(HSSFPalette palette, int b, short s, short t) {
    606         if (s == 0)
    607             return bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
    608         String borderColorStr = convertToStardColor(palette.getColor(t));
    609         borderColorStr = borderColorStr == null || borderColorStr.length() < 1 ? "#000000" : borderColorStr;
    610         return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
    611 
    612     }
    613 
    614     private static String getBorderStyle(int b, short s, XSSFColor xc) {
    615 
    616         if (s == 0)
    617             return bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
    618         if (xc != null && !"".equals(xc)) {
    619             String borderColorStr = xc.getARGBHex();// t.getARGBHex();
    620             borderColorStr = borderColorStr == null || borderColorStr.length() < 1 ? "#000000"
    621                     : borderColorStr.substring(2);
    622             return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
    623         }
    624 
    625         return "";
    626     }
    627 }

    pom.xml  (包含部分ppt转html的包)

    <!-- 二.具体依赖配置 -->
        <dependencies>
            <dependency>
                <groupId>fr.opensagres.xdocreport</groupId>
                <artifactId>fr.opensagres.xdocreport.document</artifactId>
                <version>1.0.5</version>
            </dependency>
            <dependency>
                <groupId>fr.opensagres.xdocreport</groupId>
                <artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId>
                <version>1.0.5</version>
            </dependency>
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>3.9</version>
            </dependency>
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-scratchpad</artifactId>
                <version>3.9</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.4</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itextpdf</artifactId>
                <version>5.4.3</version>
            </dependency><!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
            <dependency>
                <groupId>org.apache.pdfbox</groupId>
                <artifactId>pdfbox</artifactId>
                <version>2.0.1</version>
            </dependency>
    
    
    
        </dependencies>

    结果

     

     有问题的可以私聊我,探讨一些。

  • 相关阅读:
    CF 526F Max Mex(倍增求LCA+线段树路径合并)
    CoderForces Round526 (A~E)题解
    牛客OI周赛4-提高组 A K小生成树(kmst)
    Codeforces 1072 C
    Codeforces 1053 C
    牛客国庆集训派对Day3 B Tree
    牛客国庆集训派对Day3 I Metropolis
    牛客国庆集训派对Day3 A Knight
    牛客国庆集训派对Day3 G Stones
    Codeforces 1053 B
  • 原文地址:https://www.cnblogs.com/dalianpai/p/11664115.html
Copyright © 2020-2023  润新知