在数据处理和管理的过程中,Excel 表格常常扮演着重要的角色。除了存储常规的数据外,Excel 还支持嵌入各种对象(如图片、音频、视频等)。本文将介绍如何在 Java 中处理 Excel 表格,提取其中嵌入的对象和图片。
1. 项目依赖
首先,确保在项目中引入了必要的依赖。这里我们主要使用 Apache POI 库来处理 Excel 文件,并使用 Lombok 库简化代码。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
2. 定义数据对象
定义一个 BookObjVo
类,用于存储 Excel 表格中的书籍数据。
@Data
public class BookObjVo implements Serializable {
@Excel(name = "*书籍ID")
private Long bookId;
@Excel(name = "*书名")
private String name;
@Excel(name = "*作者名")
private String author;
@Excel(name = "*书籍类型")
private String bookType;
@Excel(name = "*epub文件")
private String epubFile;
@Excel(name = "*mp3文件")
private String mp3File;
@Excel(name = "*封面图片")
private String imageFile;
}
3. 控制器层
创建一个控制器,用于处理文件上传并调用服务层的方法。
@RestController
@RequestMapping("/test/oleObjExcel")
public class OleObjectExcelController {
@Autowired
private IOleObjectExcelService iOleObjectExcelService;
@PostMapping("/import")
public List<BookObjVo> importEpub(@RequestParam("file") MultipartFile file) {
try {
return iOleObjectExcelService.importOleObj(file);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
4. 服务接口
定义一个服务接口,声明导入方法。
public interface IOleObjectExcelService {
List<BookObjVo> importOleObj(MultipartFile file) throws Exception;
}
5. 服务实现
实现服务接口,在其中处理 Excel 文件,提取数据和嵌入对象。
@Slf4j
@Service
public class OleObjectExcelServiceImpl implements IOleObjectExcelService {
@Autowired
private OSSUtils ossUtils;
@Override
public List<BookObjVo> importOleObj(MultipartFile file) throws Exception {
InputStream is = file.getInputStream();
OPCPackage opcPackage = OPCPackage.open(is);
XSSFWorkbook workbook = new XSSFWorkbook(opcPackage);
List<BookObjVo> list = new ArrayList<>();
Sheet sheet = workbook.getSheetAt(0);
int rows = sheet.getLastRowNum();
Row headerRow = sheet.getRow(0);
Map<String, Integer> headerMap = new HashMap<>();
for (Cell cell : headerRow) {
headerMap.put(cell.getStringCellValue(), cell.getColumnIndex());
}
for (int i = 1; i <= rows; i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
BookObjVo epubVo = new BookObjVo();
epubVo.setBookId(getLongCellValue(row.getCell(headerMap.get("*书籍ID"))));
epubVo.setName(getStringCellValue(row.getCell(headerMap.get("*书名"))));
epubVo.setAuthor(getStringCellValue(row.getCell(headerMap.get("*作者名"))));
epubVo.setBookType(getStringCellValue(row.getCell(headerMap.get("*书籍类型"))));
log.info("Processing row: {}", i);
log.info("Book ID: {}", epubVo.getBookId());
log.info("Name: {}", epubVo.getName());
log.info("Author: {}", epubVo.getAuthor());
log.info("Book Type: {}", epubVo.getBookType());
for (PackagePart part : opcPackage.getParts()) {
log.info("part.getContentType()-------------------->{}", part.getContentType());
if (part.getContentType().equals("application/vnd.openxmlformats-officedocument.oleObject")) {
PackageRelationshipCollection relationships = part.getRelationships();
if (relationships.size() == 0) {
try (InputStream inputStream = part.getInputStream()) {
if (StringUtils.isEmpty(epubVo.getEpubFile())) {
processFile(epubVo, inputStream, ".epub", "epubFile");
} else if (StringUtils.isEmpty(epubVo.getMp3File())) {
processFile(epubVo, inputStream, ".mp3", "mp3File");
}
}
}
} else if (part.getContentType().equals("image/jpeg") ||
part.getContentType().equals("image/jpg") ||
part.getContentType().equals("image/png")) {
PackageRelationshipCollection relationships = part.getRelationships();
if (relationships.size() == 0) {
try (InputStream inputStream = part.getInputStream()) {
if (StringUtils.isEmpty(epubVo.getImageFile())) {
processFile(epubVo, inputStream, ".jpg", "imageFile");
}
}
}
}
}
list.add(epubVo);
}
return list;
}
private void processFile(BookObjVo epubVo, InputStream inputStream, String fileSuffix, String fileType) throws IOException {
String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + fileSuffix;
String objectName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + finalFileName;
ossUtils.uploadFileOSS(inputStream, objectName);
String ossUrl = ossUtils.getUrl(objectName);
log.info("Uploaded {} file to {}", fileType, ossUrl);
switch (fileType) {
case "epubFile":
epubVo.setEpubFile(ossUrl);
break;
case "mp3File":
epubVo.setMp3File(ossUrl);
break;
case "imageFile":
epubVo.setImageFile(ossUrl);
break;
}
}
private String getStringCellValue(Cell cell) {
if (cell == null) {
return null;
}
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue();
case NUMERIC:
return String.valueOf(cell.getNumericCellValue());
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
case FORMULA:
return cell.getCellFormula();
case BLANK:
return "";
default:
return cell.toString();
}
}
private Long getLongCellValue(Cell cell) {
if (cell == null) {
return null;
}
switch (cell.getCellType()) {
case STRING:
return Long.parseLong(cell.getStringCellValue());
case NUMERIC:
return (long) cell.getNumericCellValue();
default:
return null;
}
}
}
在这个实现中,我们通过 OPCPackage
和 XSSFWorkbook
来处理 Excel 文件。遍历表格中的每一行,提取常规数据并处理嵌入对象和图片。对于嵌入的文件和图片,我们使用自定义的 processFile
方法将其上传到 OSS(对象存储服务),并保存其 URL。
结论
本文介绍了如何在 Java 中使用 Apache POI 库处理 Excel 文件,并提取其中的嵌入对象和图片。通过这种方式,可以方便地处理 Excel 表格中的复杂数据结构,并将其应用于实际项目中。希望这篇文章能对你有所帮助。如果有任何问题或建议,欢迎留言讨论。一线网资源-全网一站式平台