小编典典

解析极大的Excel 2007文件的最佳语言

java

我的老板习惯于对我们的数据库执行查询,该查询返回数万行并将其保存到excel文件中。作为实习生,我经常不得不编写脚本来处理这些文件中的信息。到目前为止,我已经为满足脚本需求尝试了VBScript和Powershell。这两个过程都可能需要几分钟才能执行,即使是最简单的任务,这也意味着该脚本完成后将需要8小时的大部分时间。

我现在的解决方法是编写一个PowerShell脚本,该脚本从xlsx文件中删除所有逗号和换行符,将.xlsx文件保存到.csv,然后让Java程序处理数据收集和输出,并让我脚本完成后清理.csv文件。对于我当前的项目,此过程只需几秒钟,但是我不禁怀疑下一个项目是否还有更优雅的选择。有什么建议?


阅读 241

收藏
2020-09-08

共1个答案

小编典典

使用.xlsx文件时,我不断收到各种奇怪的错误。

这是一个使用Apache POI遍历.xlsx文件的简单示例。另请参阅 升级到POI
3.5,包括将现有的HSSF用户模型代码转换为SS用户模型(对于XSSF和HSSF)

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class XlsxReader {

    public static void main(String[] args) throws IOException {
        InputStream myxls = new FileInputStream("test.xlsx");
        Workbook book = new XSSFWorkbook(myxls);
        FormulaEvaluator eval =
            book.getCreationHelper().createFormulaEvaluator();
        Sheet sheet = book.getSheetAt(0);
        for (Row row : sheet) {
            for (Cell cell : row) {
                printCell(cell, eval);
                System.out.print("; ");
            }
            System.out.println();
        }
        myxls.close();
    }

    private static void printCell(Cell cell, FormulaEvaluator eval) {
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_BLANK:
                System.out.print("EMPTY");
                break;
            case Cell.CELL_TYPE_STRING:
                System.out.print(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    System.out.print(cell.getDateCellValue());
                } else {
                    System.out.print(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                System.out.print(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA:
                System.out.print(cell.getCellFormula());
                break;
            default:
                System.out.print("DEFAULT");
        }
    }
}
2020-09-08