解析Excel文件 Apache POI框架使用

本文整理了,使用Apache POI 框架解析、读取Excel文件,过程中,程序代码出现的一些问题,并解决

1、.xls 和 .xlsx

我们知道Excel文档,在Windows下,分为Excel2003 和 Excel2007.两者有一些区别,最直观的,就是后缀名不一样,分别是 .xls 和 .xlsx

使用Apache POI 解析时,需要区别对待。用不同的API去解析。

但是,却也提供了一个,统一去解析的API,那就是 org.apache.poi.ss.usermodel.WorkbookFactory;

开发,运行的时候,需要导入这样的几个 .jar 包

不然,就会出问题:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject

这个错误是由于POI包是默认不支持excel2007操作的,要加入一个xmlbeans的包xbean.jar

使用POI库,在实例化XSSFWorkbook对象时,报 Java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlOptions 的错误,经检查,是因为官方包里默认是不包含xmlbean.jar包的,需要自己添加xmlbeans.jar这个包

public void parseXml(String filename) {
    Workbook wb = null;
    try {
        wb = WorkbookFactory.create(new File(filename));
        Sheet sheet = wb.getSheetAt(0);

        for (Row row : sheet) {

            for (Cell cell : row) {
                System.out.print(getCellValue(cell) + "---");
                save(getCellValue(cell) + "---");
            }
            System.out.println();
        }
    } catch (EncryptedDocumentException e) {
        e.printStackTrace();
    } catch (InvalidFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {
        e.printStackTrace();
    }
}

2、解析文件时出现:lang.RuntimeException: Unexpected record type (org.apache.poi.hssf.record.DefaultRowHeightRecord)

解决:excel打开另存一下就可以了

3、一个可以遍历,解析文件夹下,全部Excel文件内容的代码

解析的内容,保存到了一个 .txt 文件中

已调试通过,如下:

public class ParseExcel {

    public static void main(String[] args) throws IOException {

        String path = "C:\Users\文件夹目录路径\Desktop\a01hos\img";
        File f = new File(path);
        File[] files = f.listFiles();
        System.out.println(files.length);

        File[] filesxls = f.listFiles(new FilenameFilter() {

            public boolean accept(File dir, String name) {
                if (name.endsWith(".xls") || name.endsWith(".xlsx")) {
                    return true;
                }
                return false;
            }
        });
        System.out.println("Excel文件有: " + filesxls.length);

        for (File f2 : filesxls) {
            String fileDirectPathName = f2.getCanonicalPath();
            System.out.println(fileDirectPathName);
            // System.out.println("文件名: " + f2.getName());

            new ParseExcel().parseXml(fileDirectPathName);
        }
  }
public void parseXml(String filename) {
        Workbook wb = null;
        try {
            wb = WorkbookFactory.create(new File(filename));
            Sheet sheet = wb.getSheetAt(0);

            for (Row row : sheet) {

                for (Cell cell : row) {
                    System.out.print(getCellValue(cell) + "---");
                    save(getCellValue(cell) + "---");
                }
                System.out.println();
            }
        } catch (EncryptedDocumentException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public Object getCellValue(Cell cell) {
        int type = cell.getCellType();
        String show = null;
        switch (type) {
        case Cell.CELL_TYPE_BLANK:// 空值
            show = null;
            break;
        case Cell.CELL_TYPE_BOOLEAN:// Boolean
            show = String.valueOf(cell.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_ERROR:// 故障
            show = String.valueOf(cell.getErrorCellValue());
            break;
        case Cell.CELL_TYPE_FORMULA:// 公式
            show = cell.getCellFormula();
            break;
        case Cell.CELL_TYPE_NUMERIC:// 数字
            show = String.valueOf(cell.getNumericCellValue());
            break;
        case Cell.CELL_TYPE_STRING:// 字符串
            show = cell.getStringCellValue();
            break;
        default:
            show = null;
        }
        return show;
    }
    
    /**
     * 保存字符串到文本中
     * 
     * @param str
     */
    public boolean save(String str) {
        boolean flag = false; // 声明操作标记

        String fileName = "file/test.txt"; // 定义文件名
        
        File f = new File(fileName);
        
        if(!f.exists()){
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        FileWriter fw = null; // 用来写入字符文件的便捷类
        PrintWriter out = null; // 向文本输出流打印对象的格式化表示形式类

        try {
            fw = new FileWriter(f, true); // 创建一个FileWriter
            out = new PrintWriter(fw); // 创建一个PrintWriter,以追加方式将内容插入到最后一行
            out.println(str); // 将字符串打印到文本中
            out.flush(); // 刷新缓存

            flag = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭PrintWriter
                if (out != null) {
                    out.close();
                    out = null;
                }
                // 关闭FileWriter
                if (fw != null) {
                    fw.close();
                    fw = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

}

 

 扫个红包吧!

Donate捐赠

如果我的文章帮助了你,可以赞赏我 6.66 元给我支持,让我继续写出更好的内容)

   

  (微信)                                        (支付宝)

微信/支付宝 扫一扫

原文地址:https://www.cnblogs.com/moonsoft/p/9370921.html