图谱-后端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
3.3 KiB

8 months ago
package com.teaching.backend.utils.Chapter;
/**
* ClassName: ExcelParser
* Package: com.teaching
* Description:
*
* @Author 姜钧瀚
* @Create 2024/8/3 14:58
* @Version 1.0
*/
8 months ago
import com.teaching.backend.mapper.chapter.TemporaryChapterMapper;
8 months ago
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 {
8 months ago
@Autowired
TemporaryChapterMapper temporaryChapterMapper;
8 months ago
@Autowired
IChapterService chapterService;
public List<String> parse(InputStream inputStream, String courseId) throws Exception {
OPCPackage pkg = OPCPackage.open(inputStream);
List<String> validationErrors = new ArrayList<>();
8 months ago
int totalRows = 0;
8 months ago
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();
8 months ago
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;
8 months ago
while (sheets.hasNext()) {
InputStream sheetstream = sheets.next();
InputSource sheetSource = new InputSource(sheetstream);
try {
8 months ago
sheetHandler = new SheetHandler(temporaryChapterMapper, chapterService, courseId, totalRows);
parser.setContentHandler(new XSSFSheetXMLHandler(styles, sst, sheetHandler, false));
8 months ago
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;
}
}