zoukankan      html  css  js  c++  java
  • Excel表格内容导出到页面

     

    public void addExcelBooks() throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    String filepath = request.getParameter("filepath");
    String fileType = filepath.substring(filepath.lastIndexOf("."));
    InputStream is = null;
    Workbook wb = null;
    try {
    String filedir = ServletActionContext.getServletContext().getRealPath(filepath);
    File file = new File(filedir);
    is = new FileInputStream(file);
    if (fileType.equals(".xls")) {
    wb = new HSSFWorkbook(is);
    } else if (fileType.equals(".xlsx")) {
    wb = new XSSFWorkbook(is);
    } else {
    throw new Exception("读取的不是Excel文件");
    }
    JSONArray jsonarr = new JSONArray();
    for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) {//excel的sheet
    Sheet hf = wb.getSheetAt(numSheet);
    if (hf == null) {
    continue;
    }
    JSONObject jsonChildObj = new JSONObject();
    for (int rowNum = 1; rowNum <= hf.getLastRowNum(); rowNum++) {
    Row hr = hf.getRow(rowNum);
    if (hr == null) {
    break;
    }
    Cell hxh = hr.getCell(0);
    Cell hca = hr.getCell(1);
    Cell hcb = hr.getCell(2);
    if (hca == null || hca.toString().equals("") || hcb == null || hcb.toString().equals("") || hxh == null || hxh.toString().equals("")) {
    break;
    }
    if (hxh.getCellType() != Cell.CELL_TYPE_NUMERIC) {判断类型对否excel表的第一列为书序为int类型对应的就是CELL_TYPE_NUMERIC
    jsonChildObj.put("fail", "FAIL");
    jsonarr.add(jsonChildObj);
    // throw new Exception("文件内容格式错误");
    } else {
    int xnumber = (int) hr.getCell(0).getNumericCellValue();
    String name = hr.getCell(1).getStringCellValue();
    int revision = (int) hr.getCell(2).getNumericCellValue();

    //这里转换为json类型前台通过ajax获得
    jsonChildObj.put("xnumber", xnumber);
    jsonChildObj.put("name", name);
    jsonChildObj.put("revision", revision);
    jsonarr.add(jsonChildObj);
    }
    }
    }
    jsonPrint(jsonarr);

    } catch (FileNotFoundException e) {
    throw e;
    } finally {
    if (wb != null) {
    wb = null;
    }
    if (is != null) {
    is.close();
    }
    }
    }

  • 相关阅读:
    3秒后页面跳转代码
    数据库 ""和null的在java 持久化中的区别
    去掉标签元素
    hibernate 自动封装
    hql 多对多查询
    javascript 数组
    spring mvc+mybatis整合
    collection映射
    mybatis中one2many
    mybatis中many2one
  • 原文地址:https://www.cnblogs.com/niuxi/p/7250448.html
Copyright © 2011-2022 走看看