To export data from a database query into an Excel file using Java, you can leverage Apache POI to generate the spreadsheet and populate it with query results.
public class DataExporter {
@Autowired
private RecordMapper recordMapper;
public void exportToExcel() {
File outputFile = new File("/home/vlog/report.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Report");
// Create header row
HSSFRow headerRow = sheet.createRow(0);
HSSFCellStyle centerStyle = workbook.createCellStyle();
centerStyle.setAlignment(HorizontalAlignment.CENTER);
headerRow.createCell(0).setCellValue("Date");
headerRow.createCell(1).setCellValue("Account");
headerRow.createCell(2).setCellValue("Phone");
List<Record> records = recordMapper.fetchRecords();
if (!records.isEmpty()) {
for (int i = 0; i < records.size(); i++) {
HSSFRow dataRow = sheet.createRow(i + 1);
Record current = records.get(i);
if (current.getDate() != null) {
dataRow.createCell(0).setCellValue(current.getDate());
}
if (current.getAccount() != null) {
dataRow.createCell(1).setCellValue(current.getAccount());
}
if (current.getPhone() != null) {
dataRow.createCell(2).setCellValue(current.getPhone());
}
}
}
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
}
}
}
The Record class represents the database table structure:
@Data
@Entity
@TableName("DATA_TABLE")
public class Record {
private String date;
private String account;
private String phone;
}
The corresponding mapper interface defines the query method:
public interface RecordMapper {
List<Record> fetchRecords();
}