• POI Workbook接口和HSSFWorkbook对象和XSSFWorkbook对象操作相应excel版本


    转载:https://blog.csdn.net/zb0567/article/details/71248817/

    刚开始使用new HSSFWorkbook(new FileInputStream(excelFile))来读取Workbook,对Excel2003以前(包括2003)的版本没有问题,但读取Excel2007时发生如下异常: 
    org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF) 
            该错误意思是说,文件中的数据是用Office2007+XML保存的,而现在却调用OLE2 Office文档处理,应该使用POI不同的部分来处理这些数据,比如使用XSSF来代替HSSF。 
            于是按提示使用XSSF代替HSSF,用new XSSFWorkbook(excelFile)来读取Workbook,对Excel2007没有问题了,可是在读取Excel2003以前(包括2003)的版本时却发生了如下新异常: 
    org.apache.poi.openxml4j.exceptions.InvalidOperationException: Can't open the specified file: '*.xls' 
            该错误是说,操作无效,不能打开指定的xls文件。 
            下载POI的源码后进行单步调试,发现刚开始的时候还是对的,但到ZipFile类后就找不到文件了,到网上查了下,原来是XSSF不能读取Excel2003以前(包括2003)的版本,这样的话,就需要在读取前判断文件是2003前的版本还是2007的版本,然后对应调用HSSF或XSSF来读取。 
            简而言之:由于HSSFWorkbook只能操作excel2003一下版本,XSSFWorkbook只能操作excel2007以上版本,所以利用Workbook接口创建对应的对象操作excel来处理兼容性

    @Test
    public void test6() throws Exception{
    HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream( new File("c://123.xls")));
    HSSFSheet sheet = workbook.getSheetAt(0);
    HSSFRow row =sheet.getRow(0);
    HSSFCell cell= row.getCell(0);
    System.out.println(cell.toString());
    }

    @Test
    public void test7() throws Exception{
    XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream( new File("c://456.xlsx")));
    XSSFSheet sheet = workbook.getSheetAt(0);
    XSSFRow row =sheet.getRow(0);
    XSSFCell cell= row.getCell(0);
    System.out.println(cell.toString());
    }

    @Test //利用Workbook接口和判断excel版本创建相应版本HSSFWorkbook/XSSFWorkbook对象
    public void test8() throws Exception{
    String file = "c://456.xlsx";
    boolean isExcel2003 = file.toLowerCase().endsWith("xls")?true:false;
    Workbook workbook = null;
    if(isExcel2003){
    workbook = new HSSFWorkbook(new FileInputStream(new File(file)));
    }else{
    workbook = new XSSFWorkbook(new FileInputStream(new File(file)));
    }
    Sheet sheet = workbook.getSheetAt(0);
    Row row =sheet.getRow(0);
    Cell cell= row.getCell(0);
    System.out.println(cell.toString());
    }

  • 相关阅读:
    warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
    Windows10+CLion+OpenCV4.5.2开发环境搭建
    Android解决部分机型WebView播放视频全屏按钮灰色无法点击、点击全屏白屏无法播放等问题
    MediaCodec.configure Picture Width(1080) or Height(2163) invalid, should N*2
    tesseract
    Caer -- a friendly API wrapper for OpenCV
    Integrating OpenCV python tool into one SKlearn MNIST example for supporting prediction
    Integrating Hub with one sklearn mnist example
    What is WSGI (Web Server Gateway Interface)?
    Hub --- 机器学习燃料(数据)的仓库
  • 原文地址:https://www.cnblogs.com/renjiaqi/p/11671671.html
Copyright © 2020-2023  润新知