Java导出Excel和读取Excel

↘锁芯ラ 提交于 2020-01-19 04:43:59

Java导出Excel和读取Excel

	@Override
    public List<String> readExcel(String fileName,int sheet) throws IOException {
        List result = new ArrayList();
        InputStream is = new FileInputStream(new File(fileName));
        Workbook hssfWorkbook = null;
        if (fileName.endsWith("xlsx")) {
            hssfWorkbook = new XSSFWorkbook(is);//Excel 2007
        } else if (fileName.endsWith("xls")) {
            hssfWorkbook = new HSSFWorkbook(is);//Excel 2003
        }
        Sheet hssfSheet = hssfWorkbook.getSheetAt(sheet);
        for (int rowNum = 0; rowNum < hssfSheet.getLastRowNum(); rowNum++) {
            Row hssfRow = hssfSheet.getRow(rowNum);
            if (hssfRow != null) {
                String[] arr = new String[hssfRow.getLastCellNum()];
                for(int cellNum = 0 ; cellNum < hssfRow.getLastCellNum() ; cellNum++){
                    try {
                        arr[cellNum] = hssfRow.getCell(cellNum).toString();
                    }catch (Exception e){
                        arr[cellNum] = "";
                        continue;
                    }
                }
                result.add(arr);
            }
        }
        return result;
    }

    @Override
    public void exportExcel(String fileName,String sheetName,List<String[]> result) throws IOException {
        HSSFWorkbook workbook=new HSSFWorkbook();
        HSSFSheet sheet = null;
        if(sheetName == null){
            sheet = workbook.createSheet();
        }
        sheet = workbook.createSheet(sheetName);
        for(int rowIndex = 0 ; rowIndex < result.size() ; rowIndex ++){
            HSSFRow row = sheet.createRow(rowIndex);
            String[] cellInfo = result.get(rowIndex);
            for(int cellIndex = 0 ; cellIndex < cellInfo.length ; cellIndex ++){
                HSSFCell cell = row.createCell(cellIndex);
                cell.setCellValue(cellInfo[cellIndex]);
            }
        }
        FileOutputStream outputStream = new FileOutputStream(fileName);
        workbook.write(outputStream);
        outputStream.close();
    }

测试

在这里插入图片描述

在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!