最近项目中,需要实现这么一个功能:从excel表中批量导出几万条数据,再发送给第三方接口导入数据.
话不多说,直接上代码:
从本地导出excel数据,需要先引入依赖到项目中
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.4</version> </dependency>
工具类:ExcelImport
package com.dituhui.project.api; import com.alibaba.fastjson.JSON; import com.dituhui.project.entity.PoiWgBoEntity; import com.dituhui.project.utils.HaierConstant; import com.dituhui.project.utils.HttpSyncUtil; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Author: zhangweixia * @Description: * @Date:Created in 13:36 2020/4/4 * @Modified: */ public class ExcelImport { public static void main(String[] args) throws Exception { ExcelImport excelImport = new ExcelImport(); excelImport.importExcelAction(); } //导入excel数据 public void importExcelAction() throws Exception{ //文件路径 String filePath ="E:/haier/aaa.xlsx"; XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(filePath)); XSSFSheet sheet = workbook.getSheet("Sheet1"); //获取到Excel文件中的所有行数 int rows = sheet.getPhysicalNumberOfRows(); //遍历行 List<String> list = new ArrayList<>(); for (int i = 1; i < rows; i++) { // 读取左上端单元格 XSSFRow row = sheet.getRow(i); //行不为空 if (row != null){ //获取到Excel文件中的所有的列 int cells = row.getPhysicalNumberOfCells(); //biz_id XSSFCell biz_id = row.getCell(0); String bizid = getValue(biz_id); //wg_id XSSFCell wg_id = row.getCell(1); String wgid = getValue(wg_id); //wg_code XSSFCell wg_code = row.getCell(2); String wgcode = getValue(wg_code); //POI_ID XSSFCell poi_id = row.getCell(3); String poiid = getValue(poi_id); //layer_type XSSFCell layer_type = row.getCell(4); String layertype = getValue(layer_type); //status XSSFCell status = row.getCell(5); String statu = getValue(status); PoiWgBoEntity poiWgBo = new PoiWgBoEntity(); poiWgBo.setBiz_id(bizid); poiWgBo.setPoi_id(poiid); poiWgBo.setWg_id(wgid); poiWgBo.setWg_code(wgcode); poiWgBo.setLayer_type("70"); poiWgBo.setStatus(1); poiWgBo.setOpt_type(1); String url = HaierConstant.POI_WG_URL; //调用第三方接口并返回 String feedback = HttpSyncUtil.httpSync(poiWgBo, url); list.add(feedback); } } System.out.println("总同步条数是="+list.size()); } private String getValue(XSSFCell xSSFCell){ if(null == xSSFCell){ return ""; } if (xSSFCell.getCellType() == xSSFCell.CELL_TYPE_BOOLEAN){ // 返回布尔类型的值 return String.valueOf(xSSFCell.getBooleanCellValue()); } else if (xSSFCell.getCellType() == xSSFCell.CELL_TYPE_NUMERIC){ // 返回数值类型的值 return String.valueOf(xSSFCell.getNumericCellValue()); } else { // 返回字符串类型的值 return String.valueOf(xSSFCell.getStringCellValue()); } } }