Java 读取Excel工具类

最近项目需要 写了一个读取Excel的工具 可以获取到行列的信息 其后就任意处理数据了
而且还可以生成Excel

例子:


    // 垃圾桶分组
    @Test
    public void group(){
        ExcelReadResult excelReadResult = RWexcel.Instance().readExcel("D:\\奥园位置统计.xls", true);
        System.out.println(excelReadResult.tableBody);
    }

下面输出

[[1, 7, , 95, , 39.996305, 116.386228], [2, 24, , 35, , 39.996214, 116.38624], [3, 13, , 20, , 39.996172, 116.386099], [4, 6, , 14, , 39.996101, 116.385975], [5, 8, , 15, , 39.996094, 116.385756], [6, 16, , 76, , 39.996321, 116.385793], [7, 19, , 78, , 39.995936, 116.385757], [8, 33, , 69, , 39.995713, 116.385795], [9, 23, , 2, , 39.995744, 116.386048], [10, 31, , 25, , 39.99575, 116.386459], [11, 12, , 81, , 39.995423, 116.386573], [12, 88, , 50, , 39.995396, 116.386084], [13, 93, , 11, , 39.995415, 116.385801], [14, 56, , 75, , 39.994635, 116.385896], [15, 96, , 5, , 39.994647, 116.386249], [16, 10, , 27, , 39.994652, 116.386576], [17, 61, , 3, , 39.99445, 116.386635], [18, 4, , 72, , 39.99434, 116.386669], [19, 1, , 73, , 39.994168, 116.386701], [20, 46, , 22, , 39.994095, 116.386201], [21, 51, , 53, , 39.99412, 116.385904], [22, 68, , 91, , 39.99445, 116.386234], [23, 29, , 9, , 39.994438, 116.385924], [24, 36, , 80, , 39.993986, 116.385876], [25, 37, , 45, , 39.993729, 116.38588], [26, 34, , 49, , 39.993692, 116.386129], [27, 28, , 62, , 39.993687, 116.386312], [28, 17, , 47, , 39.993504, 116.386363], [29, 54, , 59, , 39.993473, 116.385903], [30, 74, , 65, , 39.992882, 116.386213], [31, 52, , 77, , 39.992896, 116.386584], [32, 18, , 79, , 39.992659, 116.3866], [33, 48, , 58, , 39.992612, 116.386402], [34, 85, , 89, , 39.992493, 116.386431], [35, 39, , 44, , 39.992539, 116.386225], [36, 82, , 94, , 39.992651, 116.386285], [37, 26, , 64, , 39.992648, 116.385904], [38, 57, , 83, , 39.992517, 116.385839], [39, 92, , 97, , 39.992296, 116.385955], [40, 40, , 71, , 39.992302, 116.38638], [41, 66, , 86, , 39.992317, 116.386655], [42, 42, , 63, , 39.992043, 116.386723]]

代码


/**
 * @author 李鑫
 * @version 1.0
 * @date 2019/7/5 13:31
 * @desc
 */
public class RWexcel {
    /**
     * @param filePath  文件路径
     * @param hasHead   是否有表头
     * @return
     */
    public static  RWexcel rWexcel;

    // 单例模式
    public static RWexcel Instance(){
        if (rWexcel == null){
            return  new RWexcel();
        }else {
            return rWexcel;
        }
    }

    // 读取excel 返回
    public ExcelReadResult readExcel(String filePath,boolean hasHead){

        ExcelReadResult readResult = new ExcelReadResult();
        InputStream inputStream ;

        ExcelReader reader;
        try {
            inputStream =new BufferedInputStream(new FileInputStream(filePath));
        } catch (FileNotFoundException e) {
            readResult.isSuccess=true;
            readResult.fialReason = "未找到文件";
            return readResult;
        }


        char c = filePath.charAt(filePath.length()-1);
        // 根据不同的文件后缀来判断是03版之前还是之后
        if (c=='s'){
            reader = EasyExcelFactory.getReader(inputStream, new ExcelListener(readResult, hasHead));
        }else if(c=='x'){
            reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, new ExcelListener(readResult, hasHead));
        }else {
            readResult.isSuccess=true;
            readResult.fialReason = "文件格式不匹配";
            return readResult;
        }
        reader.read();
        return readResult;
    }

    // 通过输入流来解析
    public ExcelReadResult readExcelByStream(InputStream is,String suffix, boolean hasHead){
        InputStream stream = new BufferedInputStream(is);
        ExcelReadResult readResult = new ExcelReadResult();
        ExcelReader reader;
        char c = suffix.charAt(suffix.length()-1);
        // 根据不同的文件后缀来判断是03版之前还是之后
        if (c=='s'){
            reader = EasyExcelFactory.getReader(stream, new ExcelListener(readResult, hasHead));
        }else if(c=='x'){
            reader = new ExcelReader(stream, ExcelTypeEnum.XLSX, new ExcelListener(readResult, hasHead));
        }else {
            readResult.isSuccess=true;
            readResult.fialReason = "文件格式不匹配";
            return readResult;
        }
        reader.read();
        return readResult;
    }

    // 生成Excel表格

    /**
     * @param head    要创建的excel的头信息
     * @param body    要创建的excel的内部信息
     * @param name    要创建的excel的名字
     * @param parentFilePath 创建的文件放在那个文件加下
     * @param env 选择工作的环境 Linux 是 ’L‘ windows 是 ’W‘
     * @return        excel的完整路径   Windows 默认在C盘excel文件夹下
     */
    public String writeExcel(ArrayList<String> head , List<List<String>> body,  String name , String parentFilePath, char env){
        FileOutputStream stream ;
        String filepath;
        if (env=='L'){
            filepath = parentFilePath+name+".xlsx";
        }else {
            filepath = "F:\\"+name+".xlsx";
        }
        try {
            File file = new File(filepath);
            file.setReadable(true,false);
            file.setWritable(true,false);
            file.setExecutable(true,false);
            if (file.exists()){
                file.delete();
            }else {
                //
            }
            //C:\AppCode\graduateDesign-master
            stream = new FileOutputStream(filepath);
        } catch (FileNotFoundException e) {
            return null;
        }
        ExcelWriter writer = new ExcelWriter(stream, ExcelTypeEnum.XLSX);
        Sheet sheet = new Sheet(1);
        sheet.setSheetName(name);
        List<List<String>> headdata = new ArrayList<List<String>>();
        for (String string : head){
            List<String> item = new ArrayList<String>();
            item.add(string);
            headdata.add(item);
        }
        sheet.setHead(headdata);
        writer.write0(body,sheet);
        writer.finish();
        String prefUrl = "/excel/"+name+".xlsx";
        //http://39.105.219.190:8082/%E6%B7%BB%E5%8A%A0%E6%83%85%E5%86%B5.xlsx
        //http://39.105.219.190:8082/%E6%B7%BB%E5%8A%A0%E6%83%85%E5%86%B5.xlsx
        return prefUrl;
    }

    static class ExcelListener extends AnalysisEventListener {

        List<List<String>> excelBody = new ArrayList<>();

        ArrayList<String> excelHead = new ArrayList<>();

        private  boolean hasHead;

        private  int  RowNumber = 0;
        int headSize = 0;

        ExcelReadResult excelReadResult = null;

        public ExcelListener(ExcelReadResult readResult ,boolean hashead) {
            this.hasHead = hashead;
            excelReadResult = readResult;
        }

        @Override
        // 开始读取
        public void invoke(Object o, AnalysisContext analysisContext) {
            // 如果有表头 那么第一行读的是表头的信息
            if (hasHead&&analysisContext.getCurrentRowNum()==0){
                excelHead = (ArrayList<String>) o;
                headSize = excelHead.size();
            }else {
                ArrayList<String> rowBody = (ArrayList<String>) o;
                int j = headSize - rowBody.size();
                for (int i = 0; i < j ; i++) {
                    rowBody.add("");
                }
                excelBody.add(rowBody);
            }
        }
        // 读取完毕回调
        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            excelReadResult.isSuccess = true;
            excelReadResult.tableBody=excelBody;
            excelReadResult.tableHead = excelHead;
        }
    }


}

/**
 * @author 李鑫
 * @version 1.0
 * @date 2019/7/5 11:11
 * @desc
 */
public class ExcelReadResult {
    public boolean isSuccess;
    public String fialReason;
    public ArrayList<String> tableHead;
    public List<List<String>> tableBody;

    public ExcelReadResult() {
        this.tableHead = new ArrayList<>();
        this.tableBody = new ArrayList<>();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java POI是一种用于读取和写入Microsoft Office格式文件的Java API。它可以读取和写入Excel、Word和PowerPoint文件。使用Java POI读取Excel文件可以使用HSSF和XSSF API。HSSF用于读取Excel 97-2003文件格式(.xls),而XSSF用于读取Excel 2007及更高版本的文件格式(.xlsx)。使用POI读取Excel文件需要创建工作簿(Workbook)、工作表(Sheet)和行(Row)对象,然后使用这些对象来读取单元格(Cell)的值。读取Excel文件时,可以使用POI提供的各种方法来获取单元格的值、格式、样式等信息。使用Java POI读取Excel文件的工具类可以简化读取Excel文件的过程,提高代码的可读性和可维护性。 ### 回答2: Java POI 是一个 Java API,可以帮助我们读取、写入和操作 Microsoft Office 格式的文档,包括 Excel、Word 和 PowerPoint 等。在 Java 开发中,使用 Java POI 可以轻松地读取 Excel 文件。 读取 Excel 文件,需要使用工具类。下面我们来看一下如何使用 Java POI 读取 Excel 工具类。 第一步:添加依赖 在 pom.xml 文件中添加以下依赖: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 第二步:定义工具类 在项目中定义读取 Excel工具类,包含以下方法: ```java public static List<List<String>> readExcel(String filePath, int sheetIndex) throws IOException { FileInputStream fis = new FileInputStream(filePath); Workbook workbook = new XSSFWorkbook(fis); Sheet sheet = workbook.getSheetAt(sheetIndex); List<List<String>> dataList = new ArrayList<>(); for (int i = 0; i <= sheet.getLastRowNum(); i++) { List<String> rowList = new ArrayList<>(); Row row = sheet.getRow(i); if (row == null) { continue; } for (int j = 0; j < row.getLastCellNum(); j++) { Cell cell = row.getCell(j); if (cell == null) { rowList.add(""); } else { rowList.add(cell.toString()); } } dataList.add(rowList); } fis.close(); return dataList; } ``` 该方法接受 Excel 文件路径和工作表的索引,返回一个二维 List,存储了读取Excel 数据。 第三步:调用工具类 在需要读取 Excel 的地方,调用工具类的 readExcel 方法即可。 例如: ```java List<List<String>> dataList = ExcelUtils.readExcel("example.xlsx", 0); for (List<String> rowList : dataList) { for (String cellValue : rowList) { System.out.print(cellValue + "\t"); } System.out.println(); } ``` 上述示例会读取 example.xlsx 文件中第一个工作表的所有数据,并输出到控制台。 总结 Java POI 是一种强大的 Java API,可以帮助我们读取、写入和操作 Microsoft Office 格式的文档。本文介绍了使用 Java POI 读取 Excel工具类,适用于大部分 Java 项目的开发。 ### 回答3: Java POI是一个开源JAVA API,它提供了读取、写入和操作Microsoft Office格式文件的能力。其中,读取Excel文件是它的一个重要功能。 Java POI读取Excel工具类一般分为以下步骤: 1. 创建文件输入流和Workbook对象,根据文件名或流读取Excel文件; ``` // 创建文件输入流 InputStream inputStream = new FileInputStream(filePath); // 根据文件输入流,创建Workbook对象 Workbook workbook = WorkbookFactory.create(inputStream); ``` 2. 选择读取的Sheet表单,若不指定则默认读取第一个Sheet表单; ``` // 根据指定Sheet名称,获取Sheet对象 Sheet sheet = workbook.getSheet(sheetName); // 若未指定Sheet名称,则默认读取第一个Sheet if (sheet == null) { sheet = workbook.getSheetAt(0); } ``` 3. 遍历Sheet的每一行,并读取每一列的值; ``` // 遍历每一行 for (Row row : sheet) { // 遍历每一列 for (Cell cell : row) { // 获取单元格的值 String cellValue = ""; switch (cell.getCellType()) { case STRING: cellValue = cell.getStringCellValue(); break; case NUMERIC: cellValue = String.valueOf(cell.getNumericCellValue()); break; case BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case FORMULA: cellValue = cell.getCellFormula(); break; default: cellValue = ""; break; } // 打印单元格的值 System.out.println(cellValue); } } ``` 4. 关闭文件输入流和Workbook对象; ``` // 关闭输入流 if (inputStream != null) { inputStream.close(); } // 关闭Workbook if (workbook != null) { workbook.close(); } ``` 以上是Java POI读取Excel的基本操作,读取的数据可以进一步进行处理和操作,比如存储到数据库、输出到文件等。同时,Java POI也支持读取其他类型的Microsoft Office格式文件,如Word和PowerPoint等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值