Excel文件解析工具类

这是一个使用Java POI库解析Excel文件的工具类,包括读取Excel的第一张表数据,处理各种类型的单元格,并提供了文件下载功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class ExcelUtil {

    /**
     * 方法说明:解析第一张表数据
     *    
     * @param workbook
     * @return
     */
    public static Map<String, Object> parseSheet(Workbook workbook) {
        HashMap<String,Object> map = new HashMap<String, Object>();
        List<TestVO> list = new ArrayList<TestVO>();
        //读取第一张表
        Sheet sheet = workbook.getSheetAt(0);
        if (null == sheet) {
            map.put("flag", "F");
            map.put("msg", "sheet为null");
            return map;
        }
        
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();
        for (int i = firstRowNum+1; i <= lastRowNum; i++) {
            Row row = sheet.getRow(i);//获取当前行
            //读取三列
            TestVO testVO = new TestVO();
            Cell cell0 = row.getCell(0);
            Cell cell1 = row.getCell(1);
            Cell cell2 = row.getCell(2);
            testVO.setTerminalNum(getCellValue(cell0));
            testVO.setMeterNum(getCellValue(cell1));
            testVO.setTableModel(getCellValue(cell2));
            list.add(testVO);
        }
        map.put("resData", list);
        map.put("flag", "T");
        map.put("msg", "success");
        return map;
    }
    
    /**
     * 方法说明:解析excel文件
     *    
     * @param file
     * @return
     */
    public static Map<String, Object> parseExcel(File file) {
        HashMap<String,Object> map = null;
        String filePath = file.getAbsolutePath();
        String filename = file.getName();
        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
            Workbook workbook = null;

//判断excel文件名后缀
            if (filename.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(is);
            } else if (filename.endsWith(".xls")) {

//OfficeXmlFileException 为2003和2007excel版本兼容异常,出现异常io流会关闭
                try {
                    workbook = new HSSFWorkbook(is);
                } catch (OfficeXmlFileException e) {
                    is = new FileInputStream(file);
                    workbook = new XSSFWorkbook(is);
                }
            }
            map = (HashMap<String, Object>) parseSheet(workbook);
        } catch (FileNotFoundException e) {
            map.put("msg", "file not found");
            e.printStackTrace();
        } catch (IOException e) {
            map.put("msg", "created workbook is fail");
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                map.put("msg", "InputStream close exception");
                e.printStackTrace();
            }
        }
        return map;
    }
    
    /**
     * 方法说明:解析单元格格式获得值
     *    
     * @param cell
     * @return
     */
    public static String getCellValue(Cell cell){
        String cellValue = "";
        if(cell == null){
            return cellValue;
        }
        //判断数据的类型
        switch (cell.getCellType()){
            case Cell.CELL_TYPE_NUMERIC: //数字
                //读取日期
                if (DateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    cellValue = sdf.format(cell.getDateCellValue());
                } else {
                //避免excel数据科学计算法
                    DecimalFormat df = new DecimalFormat("0");
                    cellValue = df.format(cell.getNumericCellValue()).trim();
                }
                break;
            case Cell.CELL_TYPE_STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue()).trim();
                break;
            case Cell.CELL_TYPE_BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue()).trim();
                break;
            case Cell.CELL_TYPE_FORMULA: //公式
                cellValue = String.valueOf(cell.getCellFormula()).trim();
                break;
            case Cell.CELL_TYPE_BLANK: //空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }

/**
     * 方法说明:文件下载
     *    
     * @param request
     * @param response
     */

public static void downloadFile(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        File obj = null;
        // 用于显示的文件名
        String fileName = "Batch_Import.xls";
        // 获取文件路径,服务器web下路径
        String rootPath = request.getSession().getServletContext()
                .getRealPath("/");
        String path = rootPath + "/template/" + fileName;
        obj = new File(path);

        if (!obj.exists()) {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print("模板不存在,请重新上传");
            return;
        }
        InputStream blobStream = new FileInputStream(obj);
        ServletOutputStream outStream = response.getOutputStream();
        response.setContentType("application/OCTET-STREAM;charset=utf-8");
        fileName = fileName.trim();
        response.addHeader("Content-disposition", "attachment;filename="
                + new String(fileName.getBytes("gb2312"), "ISO-8859-1") + "");
        byte[] buffer = new byte[1024 * 1024];
        int nbytes = 0;
        while ((nbytes = blobStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, nbytes);
        }
        outStream.flush();
        outStream.close();
        blobStream.close();
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值