解决Java导入excel大量数据出现内存溢出的问题

问题:系统要求导入40万条excel数据,采用poi方式,服务器出现内存溢出情况。

解决方法:由于HSSFWorkbook workbook = new HSSFWorkbook(path)一次性将excel load到内存中导致内存不够。

故采用读取csv格式。由于csv的数据以x1,x2,x3形成,类似读取txt文档。

 private BufferedReader bReader;

  /**
   * 执行文件入口
   */
  public void execute() {
    try {
      if(!path.endsWith(".csv")){
        logger.info("-----该文件不是以CSV文件,请上传正确的文件格式------");
        return ;
      }
      Long startTime = System.currentTimeMillis();
      logger.info("------开始执行定时任务,时间=" + startTime);
      readCSV(path);
      Long endTime = System.currentTimeMillis();
      logger.info("------结束定时任务,时间=" + endTime + "---耗时="
          + (endTime - startTime));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 读取csv并处理数据
   * @param path
   * @throws Exception
   */
  private void readCSV(String path) throws Exception {
    File file = new File(path); 
    try {
      bReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "gbk"));
       String line = "";
        //忽略第一行标题
        for (int i = 0; i < 1; i++) { 
          line = bReader.readLine(); 
        }
        while((line = bReader.readLine()) != null){
          if (line.trim() != "") {
          //分割开来的即是对应的每个单元格,注意空的情况
            String[] result = line.split(",");

            }
          }
        } 
    } finally {
      if (bReader != null) {
        bReader.close();
      }
    }
  }

以上这篇解决Java导入excel大量数据出现内存溢出的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

若文章对您有帮助,帮忙点个赞!

0
-3
发布时间 2018-06-26 12:14:27
0 条回复(回复会通过微信通知作者)
点击加载更多评论
登录 后再进行评论
(微信扫码即可登录,无需注册)