软件编程
位置:首页>> 软件编程>> java编程>> 解决Java导入excel大量数据出现内存溢出的问题

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

作者:dandanfeng1992  发布时间:2023-05-30 08:41:20 

标签:excel,内存,溢出,java

问题:系统要求导入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();
     }
   }
 }

来源:https://blog.csdn.net/dandanfeng1992/article/details/75661096

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com