java实现在线预览--poi实现word、excel、ppt转html

java实现在线预览- -之poi实现word、excel、ppt转html

java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服务就可以了,例如永中office、office web 365(http://www.officeweb365.com/)他们都有云在线预览服务,就是要钱0.0
如果想要免费的,可以用openoffice,还需要借助其他的工具(例如swfTools、FlexPaper等)才行,可参考这篇文章http://blog.csdn.net/z69183787/article/details/17468039,写的挺细的,实现原理就是:
1.通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件;
2.通过swfTools将pdf文件转换成swf格式的文件;
3.通过FlexPaper文档组件在页面上进行展示。
当然如果装了Adobe Reader XI,那把pdf直接拖到浏览器页面就可以直接打开预览,这样就不需要步骤2、3了,前提就是客户装了Adobe Reader XI这个pdf阅读器。
我这里介绍通过poi实现word、excel、ppt转html,这样就可以放在页面上了。

word转html

package wordToHtml;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;
public class PoiWordToHtml {
 public static void main(String[] args) throws Throwable {
  final String path = "D:\\poi-test\\wordToHtml\\";
  final String file = "人员选择系分.doc";
  InputStream input = new FileInputStream(path + file);
  HWPFDocument wordDocument = new HWPFDocument(input);
  WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
    DocumentBuilderFactory.newInstance().newDocumentBuilder()
      .newDocument());
  wordToHtmlConverter.setPicturesManager(new PicturesManager() {
   public String savePicture(byte[] content, PictureType pictureType,
     String suggestedName, float widthInches, float heightInches) {
    return suggestedName;
   }
  });
  wordToHtmlConverter.processDocument(wordDocument);
  List pics = wordDocument.getPicturesTable().getAllPictures();
  if (pics != null) {
   for (int i = 0; i < pics.size(); i++) {
    Picture pic = (Picture) pics.get(i);
    try {
     pic.writeImageContent(new FileOutputStream(path
       + pic.suggestFullFileName()));
    } catch (FileNotFoundException e) {
     e.printStackTrace();
    }
   }
  }
  Document htmlDocument = wordToHtmlConverter.getDocument();
  ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  DOMSource domSource = new DOMSource(htmlDocument);
  StreamResult streamResult = new StreamResult(outStream);
  TransformerFactory tf = TransformerFactory.newInstance();
  Transformer serializer = tf.newTransformer();
  serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  serializer.setOutputProperty(OutputKeys.METHOD, "html");
  serializer.transform(domSource, streamResult);
  outStream.close();
  String content = new String(outStream.toByteArray());
  FileUtils.writeStringToFile(new File(path, "人员选择系分.html"), content, "utf-8");
 }
}

excel转html

package excelToHtml;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;


public class PoiExcelToHtml {
    final static String path = "D:\\poi-test\\excelToHtml\\";
     final static String file = "exportExcel.xls";
 public static void main(String args[]) throws Exception {

     InputStream input=new FileInputStream(path+file);
     HSSFWorkbook excelBook=new HSSFWorkbook(input);
     ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
     excelToHtmlConverter.processWorkbook(excelBook);
     List pics = excelBook.getAllPictures();
     if (pics != null) {
         for (int i = 0; i < pics.size(); i++) {
             Picture pic = (Picture) pics.get (i);
             try {
                 pic.writeImageContent (new FileOutputStream (path + pic.suggestFullFileName() ) );
             } catch (FileNotFoundException e) {
                 e.printStackTrace();
             }
         }
     }
     Document htmlDocument =excelToHtmlConverter.getDocument();
     ByteArrayOutputStream outStream = new ByteArrayOutputStream();
     DOMSource domSource = new DOMSource (htmlDocument);
     StreamResult streamResult = new StreamResult (outStream);
     TransformerFactory tf = TransformerFactory.newInstance();
     Transformer serializer = tf.newTransformer();
     serializer.setOutputProperty (OutputKeys.ENCODING, "utf-8");
     serializer.setOutputProperty (OutputKeys.INDENT, "yes");
     serializer.setOutputProperty (OutputKeys.METHOD, "html");
     serializer.transform (domSource, streamResult);
     outStream.close();

     String content = new String (outStream.toByteArray() );

     FileUtils.writeStringToFile(new File (path, "exportExcel.html"), content, "utf-8");
 }
}

ppt转html

其实只是ppt转图片,有了图片后放到页面上去,点击下一页就一张张显示就可以了。这里只介绍ppt转图片的过程

package pptToImg;

import java.awt.Dimension;   
import java.io.File;   
import java.io.FileInputStream;   
import java.io.FileNotFoundException;   
import java.io.FileOutputStream;   
import java.io.IOException;   

import java.awt.Color;   
import java.awt.Dimension;   
import java.awt.Graphics2D;   
import java.awt.geom.Rectangle2D;   
import java.awt.image.BufferedImage;   

import org.apache.poi.hslf.model.TextRun;   
import org.apache.poi.hslf.record.Slide;   
import org.apache.poi.hslf.usermodel.RichTextRun;   
import org.apache.poi.hslf.usermodel.SlideShow;   

public class PPTtoImage {   
    public static void main(String[] args) {   
        // 读入PPT文件   
        File file = new File("D:/poi-test/pptToImg/test.ppt");   
        doPPTtoImage(file);   
    }   

    public static boolean doPPTtoImage(File file) {   
        boolean isppt = checkFile(file);   
        if (!isppt) {   
            System.out.println("The image you specify don't exit!");   
            return false;   
        }   
        try {   

            FileInputStream is = new FileInputStream(file);   
            SlideShow ppt = new SlideShow(is);   
            is.close();   
            Dimension pgsize = ppt.getPageSize();   
            org.apache.poi.hslf.model.Slide[] slide = ppt.getSlides();   
            for (int i = 0; i < slide.length; i++) {   
                System.out.print("第" + i + "页。");   

                TextRun[] truns = slide[i].getTextRuns();      
                for ( int k=0;k<truns.length;k++){      
                   RichTextRun[] rtruns = truns[k].getRichTextRuns();      
                  for(int l=0;l<rtruns.length;l++){      
                       int index = rtruns[l].getFontIndex();      
                        String name = rtruns[l].getFontName();                
                        rtruns[l].setFontIndex(1);      
                        rtruns[l].setFontName("宋体");  
//                        System.out.println(rtruns[l].getText());
                   }      
                }      
                BufferedImage img = new BufferedImage(pgsize.width,pgsize.height, BufferedImage.TYPE_INT_RGB);   

                Graphics2D graphics = img.createGraphics();   
                graphics.setPaint(Color.BLUE);   
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));   
                slide[i].draw(graphics);   

                // 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径   
                FileOutputStream out = new FileOutputStream("D:/poi-test/pptToImg/pict_"+ (i + 1) + ".jpeg");   
                javax.imageio.ImageIO.write(img, "jpeg", out);   
                out.close();   

            }   
            System.out.println("success!!");   
            return true;   
        } catch (FileNotFoundException e) {   
            System.out.println(e);   
            // System.out.println("Can't find the image!");   
        } catch (IOException e) {   
        }   
        return false;   
    }   

    // function 检查文件是否为PPT   
    public static boolean checkFile(File file) {   

        boolean isppt = false;   
        String filename = file.getName();   
        String suffixname = null;   
        if (filename != null && filename.indexOf(".") != -1) {   
            suffixname = filename.substring(filename.indexOf("."));   
            if (suffixname.equals(".ppt")) {   
                isppt = true;   
            }   
            return isppt;   
        } else {   
            return isppt;   
        }   
    }  
} 

ppt转图片有个缺陷,就是ppt里不是宋体的字有些可能会变成框框。
以上都需要引入poi的jar包。
要实现在线预览,只需把转换得到的html在新标签页打开或者镶嵌到某块区域就可以展现了。



java项目中Excel文件预览

package com.linkonworks.df.busi.utils;
  
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.StringWriter;
  import javax.xml.parsers.DocumentBuilderFactory;
  import javax.xml.parsers.ParserConfigurationException;
  import javax.xml.transform.OutputKeys;
  import javax.xml.transform.Transformer;
  import javax.xml.transform.TransformerException;
  import javax.xml.transform.TransformerFactory;
  import javax.xml.transform.dom.DOMSource;
  import javax.xml.transform.stream.StreamResult;
  import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
  import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  
  
  /**
   * <p>
   * @ClassName: FilePreview
   * Description: Excel文件转为html元素
   * @date 2015年12月21日
   */
  public class FilePreview {
      /**
       * Title: convertExceltoHtml
       * Description: 将2003版Excel文件转为html标签元素
       * @param excelFile
       * @return
       * @throws IOException
       * @throws ParserConfigurationException
       * @throws TransformerException
       * @throws InvalidFormatException
       */
      public static String convertExceltoHtml(String path) throws IOException,ParserConfigurationException, TransformerException,InvalidFormatException {
         HSSFWorkbook workBook = null;
         String content = null;
         StringWriter writer = null;
         File excelFile = new File(path);
         InputStream is = new FileInputStream(excelFile);;
         //判断Excel文件是2003版还是2007版
         String suffix = path.substring(path.lastIndexOf("."));
         if(suffix.equals(".xlsx")){
             //将07版转化为03版
             Xssf2Hssf xlsx2xls = new Xssf2Hssf();
             XSSFWorkbook xSSFWorkbook = new XSSFWorkbook(is);
             workBook = new HSSFWorkbook();
             xlsx2xls.transformXSSF(xSSFWorkbook, workBook);
             
         }else{
             workBook = new HSSFWorkbook(is);
         }
         try {
             ExcelToHtmlConverter converter = new ExcelToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
             converter.setOutputColumnHeaders(false);// 不显示列的表头
             converter.setOutputRowNumbers(false);// 不显示行的表头
             converter.processWorkbook(workBook);
 
             writer = new StringWriter();
             Transformer serializer = TransformerFactory.newInstance().newTransformer();
             serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
             serializer.setOutputProperty(OutputKeys.INDENT, "yes");
             serializer.setOutputProperty(OutputKeys.METHOD, "html");
             serializer.transform(new DOMSource(converter.getDocument()),
                     new StreamResult(writer));
 
             content = writer.toString();
             writer.close();
         } finally {
             try {
                 if (is != null) {
                     is.close();
                 }
                 if (writer != null) {
                     writer.close();
                 }
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
         return content;
     }
 }


java实现web的现在预览,看效果图

在这里插入图片描述

代码实现使用到的几个jar:
在这里插入图片描述

java代码实现:

@RequestMapping(value = "resource/getExcelDataByResourceIdAsync.htm", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public ResultAsync getExcelDataByResourceIdAsync(String id) {
        Map result = new HashMap<>();
        try {
            E100 e100 = resourceListService.getByPrimaryKey(id);
            if(e100 != null){
                B012 b012 = enclosureService.getByPrimaryKey(e100.getFileId());
                File file = new File(b012.getFilePath());//获取到excel文件对象
                if(file.isFile()){//获取excel的sheet当做key值
                    List sheetsKeys = ExcelUtil.getSheets(file);//获取sheet的内容(html代码)当做value值
                    Map sheetsValues = ExcelUtil.excelToHtml(file);//存储到map对象
                    result.put("sheetsKeys", sheetsKeys);
                    result.put("sheetsValues", sheetsValues);
                }
            }
        } catch (BaseServiceException e) {
            log.error(e.getMessage(),e);
        }
        return ResultAsync.success(result);
    }

js的ajax调用:

$.ajax({
        type : 'POST',
        url :  basePath+"resource/getExcelDataByResourceIdAsync.htm",
        data : {"id" : id},
        beforeSend: function(){
            $("#loadid").show();
        },
        complete:function(){
            $("#loadid").hide();
        },
        dataType : "json",
        success : function(data, textStatus, jqXHR) {
            if (data.success && data.data) {
                data = data.data;
                var sheetsKeys = data["sheetsKeys"];
                var sheetsValues = data["sheetsValues"];
                if(sheetsKeys && sheetsValues){
                    var sheetContext = "";
                    var tableContext = "";
                    for(var i=0;i
                    if(i == 0){
                        sheetContext = "
                        "+sheetsKeys[i]+"
                        ";
                        var excelHtml = sheetsValues[sheetsKeys[i]];
                        tableContext = "
                        "+excelHtml+"
                        ";
                    }else{
                        sheetContext = "
                        "+sheetsKeys[i]+"
                        ";
                        var excelHtml = sheetsValues[sheetsKeys[i]];
                        tableContext = "
                        "+excelHtml+"
                        ";
                    }
                    $(".tab_tit").append(sheetContext);
                    $(".tab_txt").append(tableContext);
                }
            }else{
                $(".tab_infos").hide();
            }
        }
    });

html代码:

	<!--列表信息-->
    <div class="tab_infos">
   	   <ul class="tab_tit"></ul>
      <div class="tab_txt"></div>
    </div>

excel工具Util类:

package com.xucj.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExcelUtil {
    private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);

    public static List getTitltByXSLExcel(InputStream input) {
        ArrayList list = new ArrayList();
        Workbook workBook = null;
        Sheet sheet = null;
        if (!((InputStream) input).markSupported()) {
            input = new PushbackInputStream((InputStream) input, 8);
        }

        try {
            if (!POIFSFileSystem.hasPOIFSHeader((InputStream) input) && !POIXMLDocument.hasOOXMLHeader((InputStream) input)) {
                log.error("非法的输入流:当前输入流非OLE2流或OOXML流!");
            } else {
                workBook = WorkbookFactory.create((InputStream) input);
            }
        } catch (IOException arg17) {
            log.error("创建表格工作簿对象发生IO异常!原因:" + arg17.getMessage(), arg17);
        } catch (InvalidFormatException arg18) {
            log.error("非法的输入流:当前输入流非OLE2流或OOXML流!", arg18);
        }

        try {
            if (workBook != null) {
                int numberSheet = workBook.getNumberOfSheets();
                if (numberSheet > 0) {
                    sheet = workBook.getSheetAt(0);
                    int rowCount = sheet.getPhysicalNumberOfRows();
                    if (rowCount > 1) {
                        Row titleRow = sheet.getRow(0);
                        int colNum = titleRow.getPhysicalNumberOfCells();

                        for (int i = 0; i < colNum; ++i) {
                            list.add(titleRow.getCell(i).getStringCellValue());
                        }
                    }
                } else {
                    log.warn("目标表格工作簿(Sheet)数目为0!");
                }
            }
        } finally {
            try {
                if (input != null) {
                    ((InputStream) input).close();
                }
            } catch (IOException arg15) {
                ;
            }
        }

        return list;
    }

    public static List getSheets(File file) {
        ArrayList list = new ArrayList();
        Workbook workBook = null;
        Sheet sheet = null;
        Object input = null;
        try {
            input = new FileInputStream(file);
        } catch (FileNotFoundException arg16) {
            log.error("未找到指定的文件!", arg16);
        } catch (Exception arg17) {
            log.error("读取Excel文件发生异常!", arg17);
        }

        if (!((InputStream) input).markSupported()) {
            input = new PushbackInputStream((InputStream) input, 8);
        }

        try {
            if (!POIFSFileSystem.hasPOIFSHeader((InputStream) input) && !POIXMLDocument.hasOOXMLHeader((InputStream) input)) {
                log.error("非法的输入流:当前输入流非OLE2流或OOXML流!");
            } else {
                workBook = WorkbookFactory.create((InputStream) input);
            }
        } catch (IOException arg19) {
            log.error("创建表格工作簿对象发生IO异常!原因:" + arg19.getMessage(), arg19);
        } catch (InvalidFormatException arg20) {
            log.error("非法的输入流:当前输入流非OLE2流或OOXML流!", arg20);
        }

        try {
            if (workBook != null) {
                int numberSheet = workBook.getNumberOfSheets();
                if (numberSheet > 0) {
                    for (int i = 0; i < numberSheet; ++i) {
                        sheet = workBook.getSheetAt(i);
                        list.add(sheet.getSheetName());
                    }
                } else {
                    log.warn("目标表格工作簿(Sheet)数目为0!");
                }
            }
        } finally {
            try {
                if (input != null) {
                    ((InputStream) input).close();
                }
            } catch (IOException arg15) {
                ;
            }
        }
        return list;
    }

    public static Map excelToHtml(File file) {
        HashMap map = new HashMap();
        Workbook workBook = null;
        Sheet sheet = null;
        Object input = null;

        try {
            input = new FileInputStream(file);
        } catch (FileNotFoundException arg16) {
            log.error("未找到指定的文件!", arg16);
        } catch (Exception arg17) {
            log.error("读取Excel文件发生异常!", arg17);
        }

        if (!((InputStream) input).markSupported()) {
            input = new PushbackInputStream((InputStream) input, 8);
        }

        try {
            if (!POIFSFileSystem.hasPOIFSHeader((InputStream) input) && !POIXMLDocument.hasOOXMLHeader((InputStream) input)) {
                log.error("非法的输入流:当前输入流非OLE2流或OOXML流!");
            } else {
                workBook = WorkbookFactory.create((InputStream) input);
            }
        } catch (IOException arg19) {
            log.error("创建表格工作簿对象发生IO异常!原因:" + arg19.getMessage(), arg19);
        } catch (InvalidFormatException arg20) {
            log.error("非法的输入流:当前输入流非OLE2流或OOXML流!", arg20);
        }

        try {
            if (workBook != null) {
                int numberSheet = workBook.getNumberOfSheets();
                if (numberSheet > 0) {
                    for (int i = 0; i < numberSheet; ++i) {
                        sheet = workBook.getSheetAt(i);
                        map.put(sheet.getSheetName(), sheetToHtml(sheet));
                    }
                } else {
                    log.warn("目标表格工作簿(Sheet)数目为0!");
                }
            }
        } finally {
            try {
                if (input != null) {
                    ((InputStream) input).close();
                }
            } catch (IOException arg15) {
                ;
            }

        }

        return map;
    }

    public static String sheetToHtml(Sheet sheet) {
        StringBuffer html = new StringBuffer();
        boolean tempCellNum = false;
        short lastCellNum = 0;
        Workbook workbook = sheet.getWorkbook();
        boolean isCellNull = true;
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();
        sheet.getPhysicalNumberOfRows();
        if (lastRowNum == 0) {
            return "";
        } else {
            int rowNum;
            Row row;
            for (rowNum = firstRowNum; rowNum <= lastRowNum; ++rowNum) {
                row = sheet.getRow(rowNum);
                if (row != null) {
                    short arg28 = row.getLastCellNum();
                    if (arg28 > lastCellNum) {
                        lastCellNum = arg28;
                    }
                }
            }

            html.append("");

            for (rowNum = firstRowNum; rowNum <= lastRowNum; ++rowNum) {
                row = sheet.getRow(rowNum);

                for (short height = 0; height < lastCellNum; ++height) {
                    Cell td_rowSpanCount = null;
                    if (row != null) {
                        td_rowSpanCount = row.getCell(height);
                    }

                    if (td_rowSpanCount != null && td_rowSpanCount.getCellType() != 3) {
                        isCellNull = false;
                        break;
                    }
                }

                if (row != null && !row.getZeroHeight()) {
                    if (isCellNull) {
                        ;
                    }

                    int arg29 = (int) ((double) row.getHeight() / 15.625D);
                    html.append("");
                    int arg30 = 0;
                    int td_count = 0;

                    for (short cellNum = 0; cellNum < lastCellNum; ++cellNum) {
                        Cell cell = row.getCell(cellNum);
                        boolean isHidden = sheet.isColumnHidden(cellNum);
                        if (!isHidden) {
                            if (cell == null) {
                                html.append("");
                            } else {
                                CellStyle cellStyle = cell.getCellStyle();
                                String bgColor = null;
                                String fontColor = null;
                                if (workbook instanceof HSSFWorkbook) {
                                    HSSFPalette boldWeight = ((HSSFWorkbook) workbook).getCustomPalette();
                                    HSSFColor fontName = boldWeight.getColor(cellStyle.getFillForegroundColor());
                                    HSSFColor fontHeight = boldWeight.getColor(workbook.getFontAt(cellStyle.getFontIndex()).getColor());
                                    bgColor = convertToStardColor(fontName);
                                    fontColor = convertToStardColor(fontHeight);
                                } else if (workbook instanceof XSSFWorkbook) {
                                    XSSFColor arg31 = (XSSFColor) cellStyle.getFillForegroundColorColor();
                                    if (arg31 != null && arg31.getARGBHex() != null) {
                                        bgColor = "#" + arg31.getARGBHex().substring(2);
                                    }

                                    XSSFFont arg33 = ((XSSFCellStyle) cellStyle).getFont();
                                    if (arg33 != null) {
                                        arg31 = arg33.getXSSFColor();
                                        if (arg31 != null && arg31.getARGBHex() != null) {
                                            fontColor = "#" + arg31.getARGBHex().substring(2);
                                        }
                                    }
                                }

                                short arg32 = workbook.getFontAt(cellStyle.getFontIndex()).getBoldweight();
                                String arg34 = workbook.getFontAt(cellStyle.getFontIndex()).getFontName();
                                short arg35 = (short) (workbook.getFontAt(cellStyle.getFontIndex()).getFontHeight() / 20);
                                int cellReginCol = getMergerCellRegionCol(sheet, rowNum, cellNum);
                                int cellReginRow = getMergerCellRegionRow(sheet, rowNum, cellNum);
                                String align = convertAlignToHtml(cellStyle.getAlignment());
                                String vAlign = convertVerticalAlignToHtml(cellStyle.getVerticalAlignment());
                                StringBuffer tdHtml = new StringBuffer("
                                        StringBuffer tdStyle = new StringBuffer();
                                if (bgColor != null && !"".equals(bgColor.trim())) {
                                    tdStyle.append(" background-color:" + bgColor + "; ");
                                }

                                if (fontColor != null && !"".equals(fontColor.trim())) {
                                    tdStyle.append(" color:" + fontColor + "; ");
                                }

                                if (arg34 != null && !"".equals(arg34.trim()) && !"宋体".equals(arg34.trim())) {
                                    tdStyle.append(" font-family:" + arg34 + "; ");
                                }

                                if (arg32 != 400) {
                                    tdStyle.append(" font-weight:").append(arg32).append(";");
                                }

                                if (arg35 > 13) {
                                    tdStyle.append(" font-size: " + arg35 + "px;");
                                } else {
                                    tdStyle.append(" font-size: 13px;");
                                }

                                if (tdStyle != null && tdStyle.length() > 0) {
                                    tdHtml.append(" style="" + tdStyle + "" ");
                                }

                                if (!"left".equals(align)) {
                                    tdHtml.append(" align="" + align + "" ");
                                }

                                if (!"center".equals(vAlign)) {
                                    tdHtml.append(" valign="" + vAlign + "" ");
                                }

                                if (cellReginCol > 1) {
                                    tdHtml.append(" colspan="" + cellReginCol + "" ");
                                }

                                if (cellReginRow > 1) {
                                    tdHtml.append(" rowspan="" + cellReginRow + "" ");
                                    ++arg30;
                                }

                                tdHtml.append(">");
                                if (cell.getCellType() == 3) {
                                    int cellReginRowTemp = getMergerCellRegionRow(sheet, rowNum - 1, cellNum);
                                    if (cellReginRowTemp == 1) {
                                        tdHtml.append(" ");
                                        tdHtml.append("");
                                        ++td_count;
                                        html.append(tdHtml);
                                    }
                                } else {
                                    tdHtml.append(getCellValue(cell).toString());
                                    tdHtml.append("");
                                    ++td_count;
                                    html.append(tdHtml);
                                }

                                cellNum = (short) (cellNum + cellReginCol - 1);
                            }
                        }
                    }

                    html.append("
                            ");
                            isCellNull = true;
                    if (arg30 == td_count) {
                        html.append("");
                    }
                }
            }

            html.append("");
            return html.toString();
        }
    }

    private static Object getCellValue(Cell cell) {
        Object value = "";
        if (cell.getCellType() == 1) {
            value = cell.getRichStringCellValue().toString();
        } else if (cell.getCellType() == 0) {
            String forString = cell.getCellStyle().getDataFormatString();
            short dataFormat = cell.getCellStyle().getDataFormat();
            String regExNum = "0+_";
            String regExDateY = "y+";
            String regExDateM = "m+";
            String regExDateD = "d+";
            String regExDateH = "h+";
            boolean result = false;
            boolean resultDate = false;
            if (forString != null) {
                if (result = Pattern.compile(regExNum).matcher(forString).find()) {
                    result = true;
                } else if (Pattern.compile(regExDateY).matcher(forString).find() || Pattern.compile(regExDateM).matcher(forString).find() || Pattern.compile(regExDateD).matcher(forString).find()
                        || Pattern.compile(regExDateH).matcher(forString).find()) {
                    resultDate = true;
                }
            }

            if (result) {
                value = getCellNumValue(cell, value);
            } else if (resultDate) {
                Date date;
                SimpleDateFormat sdf;
                if (dataFormat != 14 && dataFormat != 176 && dataFormat != 178 && dataFormat != 180 && dataFormat != 181 && dataFormat != 182) {
                    if (dataFormat == 181) {
                        date = cell.getDateCellValue();
                        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        value = sdf.format(date);
                    } else if (dataFormat == 179) {
                        date = cell.getDateCellValue();
                        sdf = new SimpleDateFormat("yyyy年MM月dd日");
                        value = sdf.format(date);
                    } else if (dataFormat != 188 && dataFormat != 177) {
                        if (dataFormat == 31) {
                            date = cell.getDateCellValue();
                            sdf = new SimpleDateFormat("MM月dd日");
                            value = sdf.format(date);
                        }
                    } else {
                        date = cell.getDateCellValue();
                        sdf = new SimpleDateFormat("yyyy年MM月");
                        value = sdf.format(date);
                    }
                } else {
                    date = cell.getDateCellValue();
                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                    value = sdf.format(date);
                }
            } else {
                value = getCellNumValue(cell, value);
            }
        }

        if (cell.getCellType() == 3) {
            value = "";
        }

        return value;
    }

    private static Object getCellNumValue(Cell cell, Object value) {
        cell.setCellType(1);
        String tempValue = cell.getRichStringCellValue().toString();
        String value1;
        if (tempValue.indexOf(".") > -1) {
            double value_temp = Double.parseDouble(tempValue);
            if (value_temp <= 999999.0D) {
                value1 = tempValue.trim();
            } else {
                NumberFormat nf = NumberFormat.getInstance();
                nf.setGroupingUsed(false);
                value1 = nf.format(value_temp);
            }
        } else {
            value1 = tempValue.trim();
        }

        return value1;
    }

    private static int getMergerCellRegionCol(Sheet sheet, int cellRow, int cellCol) {
        int retVal = 1;
        int sheetMergerCount = sheet.getNumMergedRegions();

        for (int i = 0; i < sheetMergerCount; ++i) {
            CellRangeAddress region = sheet.getMergedRegion(i);
            int col = region.getLastColumn() - region.getFirstColumn() + 1;
            int firstRow = region.getFirstRow();
            int firstCol = region.getFirstColumn();
            int lastRow = region.getLastRow();
            int lastCol = region.getLastColumn();
            if (cellRow >= firstRow && cellRow <= lastRow && cellCol >= firstCol && cellCol <= lastCol) {
                retVal = col;
                break;
            }
        }

        return retVal;
    }

    private static int getMergerCellRegionRow(Sheet sheet, int cellRow, int cellCol) {
        int retVal = 1;
        int sheetMergerCount = sheet.getNumMergedRegions();

        for (int i = 0; i < sheetMergerCount; ++i) {
            CellRangeAddress region = sheet.getMergedRegion(i);
            int row = region.getLastRow() - region.getFirstRow() + 1;
            int firstRow = region.getFirstRow();
            int firstCol = region.getFirstColumn();
            int lastRow = region.getLastRow();
            int lastCol = region.getLastColumn();
            if (cellRow >= firstRow && cellRow <= lastRow && cellCol >= firstCol && cellCol <= lastCol) {
                retVal = row;
                break;
            }
        }

        return retVal;
    }

    private static String convertAlignToHtml(short alignment) {
        String align = "left";
        switch (alignment) {
            case 1:
                align = "left";
                break;
            case 2:
                align = "center";
                break;
            case 3:
                align = "right";
        }

        return align;
    }

    private static String convertVerticalAlignToHtml(short verticalAlignment) {
        String valign = "middle";
        switch (verticalAlignment) {
            case 0:
                valign = "top";
                break;
            case 1:
                valign = "center";
                break;
            case 2:
                valign = "bottom";
        }

        return valign;
    }

    private static String convertToStardColor(HSSFColor hc) {
        StringBuffer sb = new StringBuffer("");
        if (hc != null) {
            byte a = 64;
            short b = hc.getIndex();
            if (a == b) {
                return null;
            }

            sb.append("#");

            for (int i = 0; i < hc.getTriplet().length; ++i) {
                String str_tmp = Integer.toHexString(hc.getTriplet()[i]);
                String str;
                if (str_tmp != null && str_tmp.length() < 2) {
                    str = "0" + str_tmp;
                } else {
                    str = str_tmp;
                }

                sb.append(str);
            }
        }

        return sb.toString();
    }
}

到此搞定!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值