package com.teaching.backend.utils.Chapter; /** * ClassName: ExcelParser * Package: com.teaching * Description: * * @Author 姜钧瀚 * @Create 2024/8/3 14:58 * @Version 1.0 */ import com.teaching.backend.mapper.chapter.TemporaryChapterMapper; import com.teaching.backend.service.chapter.IChapterService; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler; import org.apache.poi.xssf.model.SharedStringsTable; import org.apache.poi.xssf.model.StylesTable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * 自定义Excel解析器 */ @Component public class ExcelParser { @Autowired TemporaryChapterMapper temporaryChapterMapper; @Autowired IChapterService chapterService; public List parse(InputStream inputStream, String courseId) throws Exception { OPCPackage pkg = OPCPackage.open(inputStream); List validationErrors = new ArrayList<>(); int totalRows = 0; try { XSSFReader reader = new XSSFReader(pkg); SharedStringsTable sst = reader.getSharedStringsTable(); StylesTable styles = reader.getStylesTable(); XMLReader parser = XMLReaderFactory.createXMLReader(); XSSFReader.SheetIterator sheets = (XSSFReader.SheetIterator) reader.getSheetsData(); SheetPreScanner preScanner = new SheetPreScanner(); while (sheets.hasNext()) { InputStream sheetstream = sheets.next(); InputSource sheetSource = new InputSource(sheetstream); try { parser.setContentHandler(new XSSFSheetXMLHandler(styles, sst, preScanner, false)); parser.parse(sheetSource); } finally { sheetstream.close(); } } totalRows = preScanner.getRowCount(); sheets = (XSSFReader.SheetIterator) reader.getSheetsData(); SheetHandler sheetHandler = null; while (sheets.hasNext()) { InputStream sheetstream = sheets.next(); InputSource sheetSource = new InputSource(sheetstream); try { sheetHandler = new SheetHandler(temporaryChapterMapper, chapterService, courseId, totalRows); parser.setContentHandler(new XSSFSheetXMLHandler(styles, sst, sheetHandler, false)); parser.parse(sheetSource); } finally { sheetstream.close(); } } validationErrors = sheetHandler.finalizeProcess(); if (!validationErrors.isEmpty()) { for (String error : validationErrors) { System.out.println("导入错误: " + error); } } else { System.out.println("数据导入成功!"); } } finally { pkg.close(); } return validationErrors; } }