使用 Java 1.8、org.apache.poi 5.1.0 和 org.apache.poi.ooxml 5.1.0。我有一個由 54 行組成的 excel 檔案。我以 5 行的塊閱讀了這個檔案。如果我到達第 47 行,它會跳過該行并給我新塊的第一行,而它應該給我現在塊上方的第一個空行。
使用除錯器,我可以看到它從第 46 行轉到第 48 行,而我預計第 47 行。在第 51 行添加一個斷點(請參閱 java 代碼中的注釋以了解該位置)。您可以看到 currentRow 屬性 'r' 如何從第 46 行跳到第 48 行。
我不知道為什么會發生這種情況,但它毀了我的一天并使我的程式毫無用處。
您可以在下面找到我的檔案。我把它降到最低限度,同時仍然使錯誤可重現。
我的 build.gradle 檔案
plugins {
id 'java'
id 'application'
}
group 'nl.karnhuis'
sourceCompatibility = 1.8
application {
mainClass = 'nl.karnhuis.test.Testfile'
}
repositories {
mavenCentral()
maven {
url "https://mvnrepository.com/artifact"
}
}
dependencies {
implementation 'org.apache.poi:poi:5.1.0'
implementation 'org.apache.poi:poi-ooxml:5.1.0'
}
我的 gradle.settings 檔案
rootProject.name = 'testfile'
我的Java代碼
package nl.karnhuis.test;
import java.io.*;
import java.util.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class Testfile {
public void run() {
File inputFile = new File("schema.xlsx");
handleFile(inputFile);
}
private void handleFile(File inputFile) {
try {
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(inputFile);
// Get first/desired sheet from the workbook
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
Row currentRow = null;
// Go over all rows
while (iterator.hasNext()) {
if (checkForLastLine(currentRow)) {
break;
}
currentRow = iterator.next();
// First two rows can be skipped.
if ((currentRow.getRowNum()) < 2) {
continue;
}
currentRow = iterator.next();
// do something important
currentRow = iterator.next();
// do something important
currentRow = iterator.next();
// do something important
// The next row is empty, so it can be skipped.
currentRow = iterator.next();
System.out.println(currentRow.getRowNum()); //Add breakpoint here
}
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
}
}
private boolean checkForLastLine(Row currentRow) {
if (currentRow == null) {
return false;
} else {
for (Cell currentCell : currentRow) {
// Reached end of file? Get out of da loop!
return currentCell.getColumnIndex() == 0
&& (currentCell.getStringCellValue().trim().startsWith("primaire")
|| currentCell.getStringCellValue().trim().startsWith("secondaire"));
}
}
return false;
}
public static void main(String[] args) {
Testfile mc = new Testfile();
mc.run();
}
}
The excel file can be downloaded from https://www.karnhuis.nl/schema.xlsx
uj5u.com熱心網友回復:
Excel 中的空行似乎不是以相同的方式創建的。嘗試在第 47 行的第一個單元格中寫入一些內容并再次運行。該行將在您的班級中正確列出。即使在洗掉內容并再次擁有空行之后,它也會起作用。
Apache POI 具有邏輯行(具有或以前具有內容)的概念,并且不會回傳始終為空的行。如果您無法控制 Excel 檔案的生成方式,請不要使用計數行。例如,您可以在第一列中查找文本,然后計算 4 行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/357729.html
標籤:java excel apache-poi
