excel表格数据读取(1)--JXL方式(不支持xlsx格式)

一、maven依耐

<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
    <dependency>
        <groupId>net.sourceforge.jexcelapi</groupId>
        <artifactId>jxl</artifactId>
        <version>2.6.12</version>
    </dependency>

二、示例代码

/**
     * @Title: readExcel 
     * @Description: JXL读取excel表格数据
     * @param filePath文件路径
     * @return
     * @throws IOException
     * @throws BiffException
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private static List readExcel(String filePath) throws IOException, BiffException {
        List list = new ArrayList();
        // 创建输入流
        InputStream stream = new FileInputStream(filePath);
        // 获取Excel文件对象
        Workbook rwb = Workbook.getWorkbook(stream);
        // 获取文件的指定工作表 默认的第一个
        Sheet sheet = rwb.getSheet(0);
        // 行数(表头的目录不需要,从1开始)
        for (int i = 0; i < sheet.getRows(); i++) {
            // 创建一个数组 用来存储每一列的值
            String[] str = new String[sheet.getColumns()];
            Cell cell = null;
            // 列数
            for (int j = 0; j < sheet.getColumns(); j++) {
                // 获取第i行,第j列的值
                cell = sheet.getCell(j, i);
                str[j] = cell.getContents();
            }
            // 把刚获取的列存入list
            list.add(str);
        }
        return list;
    }

三、测试代码

@SuppressWarnings("rawtypes")
    public static void main(String args[]) throws Exception {
        List list = readExcel("D:\\test.xls");// 不支持xlsx格式的表格
        // 遍历获取每一行的内容
        for (int i = 0; i < list.size(); i++) {
            String[] row = (String[]) list.get(i);
            // 遍历获取每一行的每一列的内容
            for (String string : row) {
                System.out.print(string + "\t");
            }
            System.out.println();
        }
    }

猜你喜欢

转载自blog.csdn.net/wgq3773/article/details/81113325
今日推荐