Время прочтения: 2 мин.

Итак, задачу экспорта данных из баз данных в Excel будем решать с помощью языка программирования Java, и библиотеки Apache POI (SXSSF – для работы с большими наборами данных, низким объемом памяти).

Настройка зависимостей в конфигурационном файле maven pom.xml.

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.0.0</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.0.0</version>
</dependency>

Загружать запросы в БД будем из текстового файла

queryTxt = "";
File file = new File(fileName);
if(file.exists()) {
    System.out.println("Файл в обработке:" + file.getName());
    try (BufferedReader b = new BufferedReader(new InputStreamReader(new FileInputStream(file), "CP1251"));)
       {
        String readLine = "";
        while ((readLine = b.readLine()) != null) {
            queryTxt += readLine;
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
} else {
    queryTxt = null;
}

Обращение к БД

public ResultSet findByAllPrSt(String query) {
    try {
        PreparedStatement stmt = dataSource.getConnection().prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        ResultSet rs = stmt.executeQuery();
        return rs;
    } catch (SQLException e) {
        e.printStackTrace();
        loggerTBL.error(e.getMessage(), e);
        return null;
    }

Формирование данных в Excel

//
Row row;
Cell cell;
int columns = getCountColumn();
//
try {
    resultSet.setFetchSize(100);
    while (resultSet.next()) {
        row = sheet.createRow(iRow);
        for (int j = 0; j <= columns - 1; j++) {
            cell = row.createCell(j);
            //String address = new CellReference(cell).formatAsString();
            cell.setCellValue(resultSet.getString(j + 1));
        }
        iRow++;
        if (iRow % 2000 == 0) {
            System.out.println("Записей: " + iRow);
            ((SXSSFSheet) sheet).flushRows(2000);
        }
    }

} catch (SQLException throwables) {
    throwables.printStackTrace();
    loggerXLS.error(throwables.getMessage(), throwables);
} catch (IOException e) {
    e.printStackTrace();
    loggerXLS.error(e.getMessage(), e);
}

Здесь для ограничения расхода памяти, при очень больших объёмах данных использую разбивку выгрузки по 2000+- записей (строка ((SXSSFSheet) sheet).flushRows(2000);).

Процедура формирования и экспорта данных.

ResultSetToExcel resultSetToExcel = new ResultSetToExcel();
resultSetToExcel.setFileName(outFileName);
resultSetToExcel.openBook();
for (String qu : queryList) {
    System.out.println(qu);
    //
    try {
        System.out.println("Используется сервер " + setting.getServerName() + " типа:=" + setting.getTypeServer());
        ResultSet rsProm;
        if(setting.getTypeServer().equals("oracle")) {
            rsProm = oracleDaoJdbc.findByAllPrSt(qu);
        } else {
            rsProm = mssqlDaoJdbc.findByAllPrSt(qu);
        }
        //
        resultSetToExcel.setResultSet(rsProm);
        //Загаловок на странице Excel
        resultSetToExcel.createHeaderSheet();
        //Формирование листа
        resultSetToExcel.writeIntoExcelSXSSFMulti();
        //
        rsProm.close();
    } catch (SQLException e) {
        e.printStackTrace();
        loggerML.error(e.getMessage(), e);
    }
}
//Запись в файл
resultSetToExcel.writeBook();
int iCountRoe = resultSetToExcel.getiRow();
System.out.println("Всего записей:= " + iCountRoe);

Весь проект вы можете найти на Pivansm / jvmbasetoxls — Bitbucket