我有一个大字文档(超过 10,000 行),其中包含必须使用 Java 将其转换为 excel 的信息表。我正在使用 apache poi 来提取表格并将其保存到 excel 中。我有以下代码,它在 iMac 上的行子集上运行。但是,在完整文档上运行代码时出现堆空间异常:
public class WordExtractor {
public static void main(String[] args) {
try {
File inputFile = new File("table.docx");
POITextExtractor extractor = ExtractorFactory.createExtractor(inputFile);
String text = extractor.getText();
BufferedReader reader = new BufferedReader(new StringReader(text));
String line = null;
boolean breakRead = false;
int rowCount = 0;
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("sheet1");
while (!breakRead) {
line = reader.readLine();
if (line != null) {
Row row = sheet.createRow(rowCount);
StringTokenizer st = new StringTokenizer(line, "\t");
int cellnum = 0;
while (st.hasMoreTokens()) {
Cell cell = row.createCell(cellnum++);
String token = st.nextToken();
System.out.println(" = " + token);
cell.setCellValue(token);
}
} else {
breakRead = true;
}
rowCount++;
}
try {
FileOutputStream out =
new FileOutputStream(new File("new.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}