所以我正在尝试编写一款程序,用于在Excel文件的某一行中扫描特定模式。即在N后跟任何字母,然后是S或T(每个字母占据一个单元格)。
问题是,我使用的Excel文件非常庞大,大约有3000行和近1000列。我试图仅在前60行中搜索此模式,以减少Java堆空间。如何修改算法以实现此目的?我仍然遇到内存溢出异常。
我的代码如下:
问题是,我使用的Excel文件非常庞大,大约有3000行和近1000列。我试图仅在前60行中搜索此模式,以减少Java堆空间。如何修改算法以实现此目的?我仍然遇到内存溢出异常。
我的代码如下:
import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
public int Reader(File file) throws IOException, EncryptedDocumentException, InvalidFormatException {
FileInputStream fis = new FileInputStream(file);
String filepath = file.getPath();
Workbook wb = WorkbookFactory.create(new File(filepath));
XSSFSheet sheet = (XSSFSheet) wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
ArrayList<Integer> list = new ArrayList<Integer>();
int rows;
int cols = 0;
int temp = 0;
rows = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < 10 || i < 60; i++) {
row = sheet.getRow(i);
if (row != null) {
temp = sheet.getRow(i).getPhysicalNumberOfCells();
if (temp > cols)
cols = temp;
}
}
for (int r = 0; r <= 60; r++) {
row = sheet.getRow(r);
if (row != null) {
for (int c = 0; c <= cols; c++) {
int numblanks = 0;
cell = row.getCell((short) c);
if (cell != null) {
//System.out.print(cell + "\t\t");
} else {
//System.out.print("\t\t");
}
if (cell != null && cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
if ("N".equals(cell.getStringCellValue())) {
for (int k = c; k <= cols; k++) {
if ("-".equals(row.getCell(k).getStringCellValue())) {
numblanks++;
continue;
}
if ("S".equals(row.getCell(c + 2 + numblanks).getStringCellValue())
|| "T".equals(row.getCell(c + 2 + numblanks).getStringCellValue())) {
list.add((int) sheet.getRow(1).getCell(c).getNumericCellValue());
break;
}
}
}
}
}
System.out.println();
}
}
System.out.println();
System.out.println("Rows: " + rows);
System.out.println("Columns: " + cols);
System.out.println(list);
return temp;
}
}
ExecuteExcel4Macro("'"&path&"["&file&"]"&sheet&"'!"&range)
来获取值而不打开文件...但我怀疑Java中是否有类似的东西...但也许您可以使用一些转换或创建一个“自动运行”工作簿,它使用此功能仅为原始文件的一部分创建副本...只是一个想法。 - Dirk ReichelXPath
查询,并更轻松地获取信息。 - Dominique