首页 > 编程语言 >Java使用POI导入excel记录

Java使用POI导入excel记录

时间:2024-08-08 15:28:36浏览次数:6  
标签:Java String POI excel name getStringCellValue getCell manufacturer row

1.controller:

@PostMapping("/import-excel")
@Transactional
public AjaxResult importExcel(@RequestPart(value = "file") MultipartFile file) throws Exception {
String result = manufacturerService.importExcel(file);
return AjaxResult.success(result);
}

2.service:

String importExcel(MultipartFile file) throws Exception;

3.Impl:

@Override
@Transactional
public String importExcel(MultipartFile file) throws Exception {
List<Manufacturer> manufacturerList = new ArrayList<>();
String fileName = file.getOriginalFilename();
assert fileName != null;
String name = fileName.substring(0, fileName.indexOf("."));
String hzm = fileName.substring(name.length() + 1);
if (StringUtils.equals(hzm, "xlsx")) {
//根据路径获取这个操作excel表格
XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
//根据页面index 获取sheet页
XSSFSheet sheet = wb.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
for (int i = 1; i <= lastRowNum; i++) {
XSSFRow row = sheet.getRow(i); // 获取行
if (row != null) {
List<String> list = new ArrayList<>();
for (int j = 0; j <= 8; j++) {
if (row.getCell(j) != null) {
row.getCell(j).setCellType(CellType.STRING);
String value = row.getCell(j).getStringCellValue();
if (value != null && !"".equals(value))
list.add(value);
} else {
row.createCell(j);
}
}
if (!list.isEmpty()) {
Manufacturer manufacturer = new Manufacturer();
if (StringUtils.equals(hzm, "xlsx")) {
manufacturer.setName(row.getCell(1).getStringCellValue());
manufacturer.setCredit(row.getCell(2).getStringCellValue());
manufacturer.setAbbreviation(row.getCell(3).getStringCellValue());
manufacturer.setAddress(row.getCell(4).getStringCellValue());
manufacturer.setContactPerson(row.getCell(5).getStringCellValue());
String nameExcel = row.getCell(6).getStringCellValue();
if (!StringUtils.isEmpty(nameExcel)) {
DistrictDict dict = recManufacturerDao.findByManufacturerName(nameExcel);
manufacturer.setDescriptionId(dict.getId());
}
manufacturer.setContactPhone(row.getCell(7).getStringCellValue());
String categoryNameExcel = row.getCell(8).getStringCellValue();
if (!StringUtils.isEmpty(categoryNameExcel)) {
DevCategory devCategory = devCategoryMapper.findByCategoryName(categoryNameExcel);
manufacturer.setDeviceCategoryId(devCategory.getId());
}
}
manufacturerList.add(manufacturer);
}
} else {
row = sheet.createRow(i);
}
}
} else {
throw new RuntimeException("请您导入后缀为:xlsx类型的Excel文件");
}
Map<String, Manufacturer> nameMapManuParam = Map.of();
if (!CollectionUtils.isEmpty(manufacturerList)) {
nameMapManuParam = manufacturerList.stream()
.filter(item -> item.getName() != null).distinct()
.collect(Collectors.toMap(Manufacturer::getName, Manufacturer -> Manufacturer));
}
List<Manufacturer> manuListDB = recManufacturerDao.findAllManu();
Set<String> dbManuName = manuListDB.stream().map(Manufacturer::getName).collect(Collectors.toSet());
List<Manufacturer> newManuList = nameMapManuParam.keySet().stream().filter(nameParam -> !dbManuName.contains(nameParam)).map(nameMapManuParam::get).collect(Collectors.toList());
int insertNum = 0;
if (!CollectionUtils.isEmpty(newManuList)) {
insertNum = recManufacturerDao.insertBatch(newManuList);
}
List<Manufacturer> beUpdateList = nameMapManuParam.keySet().stream().filter(dbManuName::contains).map(nameMapManuParam::get).collect(Collectors.toList());
int updateNum = 0;
if (!CollectionUtils.isEmpty(beUpdateList)) {
recManufacturerDao.updateByExcel(beUpdateList);
updateNum = beUpdateList.size();
}
return "成功导入:" + (insertNum + updateNum) + "条数据。新增:" + insertNum + "条数据; 更新:" + updateNum + "条数据";
}

4.Mapper:

int insertBatch(@Param("manufacturerList") List<Manufacturer> manufacturerList);
Integer updateByExcel(@Param("beUpdateList") List<Manufacturer> beUpdateList);

5.xml:

<insert id="insertBatch">
INSERT INTO rec_manufacturer ( abbreviation, address, contact_person, contact_phone, credit, name, description_id, device_category_id)
VALUES
<foreach collection="manufacturerList" item="manufacturer" separator=",">
(#{manufacturer.abbreviation}, #{manufacturer.address}, #{manufacturer.contactPerson}, #{manufacturer.contactPhone}, #{manufacturer.credit}, #{manufacturer.name}, #{manufacturer.descriptionId}, #{manufacturer.deviceCategoryId})
</foreach>
</insert>
<update id="updateByExcel" parameterType="integer">
<foreach collection="beUpdateList" item="d" separator=";">
UPDATE rec_manufacturer
<set>
<if test="d.abbreviation != '' and d.abbreviation != null">
abbreviation = #{d.abbreviation},
</if>
<if test="d.address != '' and d.address != null">
address = #{d.address},
</if>
<if test="d.contactPerson != '' and d.contactPerson != null">
contact_person = #{d.contactPerson},
</if>
<if test="d.contactPhone != '' and d.contactPhone != null">
contact_phone = #{d.contactPhone},
</if>
<if test="d.credit != '' and d.credit != null">
credit = #{d.credit},
</if>
<if test="d.name != '' and d.name != null">
name = #{d.name},
</if>
<if test="d.descriptionId != '' and d.descriptionId != null">
description_id = #{d.descriptionId},
</if>
<if test="d.deviceCategoryId != '' and d.deviceCategoryId != null">
device_category_id = #{d.deviceCategoryId},
</if>
</set>
where name = #{d.name}
</foreach>
</update>

 

标签:Java,String,POI,excel,name,getStringCellValue,getCell,manufacturer,row
From: https://www.cnblogs.com/sensenh/p/18349023

相关文章

  • java进阶面向对象总结二
    1.接口继上次总结,接口是由常量和抽象方法组成,但为了增强接口功能,在jdk1.8之后可以定义含方法体的默认方法,静态方法(版本1.9之后),私有方法,他们分别用defult,static,private修饰2.内部类成员内部类:就是类里面的一个普成员外部类名.内部类名对象名=new外部类().new内部类();out......
  • 【原创】java+swing+mysql教材管理系统设计与实现
    个人主页:程序员杨工个人简介:从事软件开发多年,前后端均有涉猎,具有丰富的开发经验博客内容:全栈开发,分享Java、Python、Php、小程序、前后端、数据库经验和实战开发背景:随着高校教育的发展,学校规模越来越大,管理任务也越来越复杂。教材管理作为高校管理中的重要一环,其复杂性......
  • 【全网独家】java 九宫格拼图游戏(代码+测试部署)
    介绍九宫格拼图是一种经典的益智游戏,玩家需要将一幅图像打乱并重新排列,从而恢复原图。游戏通常以一个3x3的网格形式展现,每个方块包含图片的一部分。应用使用场景教育:帮助提高儿童的逻辑思维能力和动手能力。娱乐:提供消遣和挑战,适用于所有年龄段的玩家。认知训练......
  • java笔记7
    12.异常什么是异常异常是指程序运行过程中发生的不正常情况,它中断了正常的指令流程。Java异常类结构图Java异常层次结构基于Throwable类,主要分为两大类:Error:表示编译时和系统错误(如OutOfMemoryError),通常是不可恢复的。Exception:表示程序运行中可以捕获并处理的异常。Erro......
  • Java内存管理
    任何平台的JVM管理内存的方式是相同的JVM如何管理内存:程序运行前,JVM会向操作系统申请一块内存,然后加载运行JAVA程序,如果不够,就继续申请新内存,直到运行成功或达到内存上限(默认64M)。内存会划分为几个逻辑区域堆占内存最多存放:对象,引用类型的数据,new创建的对象,只包含对象的......
  • java之多线程篇
    一、基本概念1.什么是线程?线程就是,操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。简单理解就是:应用软件中互相独立,可以同时运行的功能2.什么是多线程?有了多线程,我们就可以让程序同时做多件事情3.多线程的作用?提高效率4.线程的应用场......
  • java之反射篇(上)——基本使用
    目录一、什么是反射二、获取class对象的3种方法三、反射获取构造方法四、反射获取成员变量五、反射获取成员方法 六、反射的作用 七、反射的两种使用方式1.Demo1保存信息2.Demo2结合配置文件获取类信息一、什么是反射反射允许对成员变量,成员方法和构造方法的信......
  • from type [java.lang.String] to type [org. apache.kafka.clients.consumer.Consume
    kafka消费消息的时候,报错Noconverterfoundcapableofconvertingfromtype[java.lang.String]totype[org.apache.kafka.clients.consumer.ConsumerRecord<??>,没有消费到数据,这种情况可能是发送方发送的数据是封装了多个ConsumerRecord<??>对象发送过来的,需要用Consume......
  • ArcGIS API for JavaScript 3.x 到 4.x 的升级手册
    众所周知,3.x版本主要是构建二维地图,且基本不会再添加新功能;而4.x版本主要是构建于三维地图,与3.x相比并不是简单的升级,基本上就是重写了。所以当我们需要把API从3.x升级到4.x时,应用程序基本上是需要重写的,这里将对API升级过程中涉及到的相关变动进行记录与描述。以下......
  • Java 中 Exception 和 Error 有什么区别?
    1.ExceptionException代表程序正常运行过程中可以预料到的意外情况,应该被开发者捕获并进行相应处理。2.ErrorError指在正常情况下不太可能出现的情况。大部分Error导致程序处于不正常、不可恢复的状态,所以不便也不需被开发者捕获,因为这个情况下你捕获了也无济于事......