POI stellt zwei Implementierungsklassen für Excel-Dateien bereit, HSSFWrorBook und XSSFWorkBook. Erstere eignet sich für alte Versionen von Excel-Dateien mit dem Suffix „.xls“, während letztere für das Suffix „.xlsx“ geeignet ist.
Excel analysieren
Erstellen Sie ein Instanziierungsobjekt der WookBook-Klasse
Erstellen Sie ein Instanziierungsobjekt der WookBook-Klasse und erstellen Sie gleichzeitig einen Eingabestream zum Lesen der Datei und lesen Sie sie Schicht für Schicht entsprechend der Struktur der Datei.
//方式1
try (Workbook workbook = new XSSFWorkbook();
FileInputStream in = new FileInputStream("D:\\test\\1627356552686.xlsx")) {
} catch (IOException e) {
e.printStackTrace();
}
try (//方式2 通过匿名子类
Workbook workbook1 = new XSSFWorkbook(new FileInputStream("D:\\test\\1627356552686.xlsx"))) {
} catch (IOException e) {
e.printStackTrace();
}
Arbeitsmappe besorgen
//根据名称获取
Sheet sheet = workbook.getSheet("yyyy");
//根据下标获取第一个工作簿
Sheet sheet = workbook.getSheetAt(0);
Rufen Sie die Datenzeilen in der aktuellen Arbeitsmappe ab
//遍历所有行
for(Row row : sheet) {
System.out.println(row);
}
//遍历部分行
// sheet.getLastRowNum():总行数
for (int i = 0; i < sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
System.out.println(row);
}
Rufen Sie jede Zelle der aktuellen Zeile ab
Cell cell = row.getCell(0); //得到第一个单元格
cell.getNumericCellValue() //得到第一个单元格的内容
// 也可以使用foreach进行单元格的遍历
for(Cell cell : row) {
}
Schreiben Sie in Excel
Erstellen Sie ein Instanziierungsobjekt der WookBook-Klasse
Das gleiche wie oben
Arbeitsmappe erstellen
Sheet sheet1 = workbook.createSheet();
//也可以自定义工作簿名称
Sheet sheet2 = workbook.createSheet("y");
Datenzeile erstellen
Row row = sheet.createRow(0); //创建当前工作簿的第一行
Erstellen Sie Zellen und schreiben Sie Inhalte
Cell cell = row.createCell(0); //创建第一个单元格
//设置当前单元格的内容
cell.setCellValue(UUID.randomUUID().toString());
Zellen formatieren
// 创建单元格样式
DataFormat dataFormat = workbook.createDataFormat();
Short formatCode = dataFormat.getFormat("yyyy-MM-dd HH:mm:ss");
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(formatCode);
// 为当前行创建单元格
Cell cell1 = row.createCell(1);
cell1.setCellStyle(cellStyle); // 设置单元格样式
cell1.setCellValue(new Date()); // 保存当前日期时间至本单元格
//设置单元格的水平对齐类型。 此时水平居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);
// 设置单元格的垂直对齐类型。 此时垂直靠底边
cellStyle.setVerticalAlignment(VerticalAlignment.BOTTOM);
In eine Excel-Datei schreiben
Das Schreiben des WorkBook-Objekts wird verwendet!
workbook.write(out);
Schreibbeispiel
public static void downloadImportTemplate() throws Exception {
String fileName = “xx”
File fileTemplate = new File(fileName);
FileInputStream is = new FileInputStream(fileTemplate);
XSSFWorkbook workbook = new XSSFWorkbook(is);
XSSFSheet sheet = workbook.getSheetAt(0);// 获取第1个工作簿
XSSFRow row0 = sheet.createRow(0);// 创建第1行
XSSFFont cellFont = workbook.createFont();// 创建样式
cellFont.setFamily(FontFamily.DECORATIVE);
XSSFDataFormat df = workbook.createDataFormat();
cellFont.setColor((short)32767);
XSSFCellStyle teamCellStyle = workbook.createCellStyle();
teamCellStyle.setAlignment(HorizontalAlignment.CENTER);
teamCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
teamCellStyle.setDataFormat(df.getFormat("@"));
teamCellStyle.setFillForegroundColor(new XSSFColor(new Color(236, 238, 238)));
teamCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
teamCellStyle.setBorderTop(BorderStyle.THIN);
teamCellStyle.setBorderBottom(BorderStyle.THIN);
teamCellStyle.setBorderRight(BorderStyle.THIN);
XSSFCell cell = row0.createCell(0);// 创建第1行的第1列
cell.setCellStyle(teamCellStyle);// 为单元格设置样式
cell.setCellValue(new XSSFRichTextString("aa"));// 设置第1行第1列的内容
// 后面每1行每1列都像前3行那样写,此处不再赘述
workbook.write(out);// excel写入workbook
out.flush();
out.close();
return null;
}
Frage
Während des Entwicklungsprozesses Workbook workbook1 = new XSSFWorkbook(new FileInputStream("D:\\test\\1627356552686.xlsx"))
wurde ein Fehler gemeldet:
org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
Dies ist auf ein Problem mit der Excel-Version zurückzuführen. Wir haben die Methode zum Parsen der Excel-Version 2003 (.xls) verwendet, um die Ausnahme zu analysieren, die nach dem Parsen der Excel-Version 2007 (.xlsx) ausgelöst wurde. Da für die Analyse je nach Excel-Version unterschiedliche Objekte verwendet werden müssen, können wir einfach eine Beurteilung anhand des Dateisuffixes treffen, zum Beispiel:
//获得原始文件名
String oriName = myfile.getOriginalFilename();
if (oriName.endsWith("xls")) {
//使用 HSSFWorkbook 解析
} else {
//使用 XSSFWorkbook 解析
}
Der Quellcode in der Funktion WorkbookFactory.create() lautet wie folgt:
/**
* Creates the appropriate HSSFWorkbook / XSSFWorkbook from
* the given InputStream.
* Your input stream MUST either support mark/reset, or
* be wrapped as a {@link PushbackInputStream}!
*/
public static Workbook create(InputStream inp) throws IOException, InvalidFormatException {
// If clearly doesn't do mark/reset, wrap up
if(! inp.markSupported()) {
inp = new PushbackInputStream(inp, 8);
}
if(POIFSFileSystem.hasPOIFSHeader(inp)) {
return new HSSFWorkbook(inp);
}
if(POIXMLDocument.hasOOXMLHeader(inp)) {
return new XSSFWorkbook(OPCPackage.open(inp));
}
throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
}
Da sowohl HSSFWorkbook als auch XSSFWorkbook die Workbook-Schnittstelle implementieren, WorkbookFactory.create()
wird in der Funktion die Version des aktuell eingehenden Excel-Dateistreams beurteilt und je nach Version unterschiedliche Workbook-Objekte zurückgegeben. Sie können also poi-ooxml WorkbookFactory.create(inputStream)
zum Erstellen einer Arbeitsmappe verwenden.