(JTable table)
| 309 | } |
| 310 | |
| 311 | public static void exportTableToExcel(JTable table) { |
| 312 | XSSFWorkbook workbook = new XSSFWorkbook(); |
| 313 | |
| 314 | // 创建一个包含整个表的工作表 |
| 315 | XSSFSheet completeSheet = workbook.createSheet("Complete Table"); |
| 316 | |
| 317 | // 创建表头 |
| 318 | XSSFRow headerRow = completeSheet.createRow(0); |
| 319 | for (int i = 0; i < table.getColumnCount(); i++) { |
| 320 | headerRow.createCell(i).setCellValue(table.getColumnName(i)); |
| 321 | } |
| 322 | |
| 323 | // 写入整个表的数据 |
| 324 | for (int i = 0; i < table.getRowCount(); i++) { |
| 325 | XSSFRow dataRow = completeSheet.createRow(i + 1); |
| 326 | for (int j = 0; j < table.getColumnCount(); j++) { |
| 327 | Object value = table.getValueAt(i, j); |
| 328 | String text = (value == null) ? "" : value.toString(); |
| 329 | dataRow.createCell(j).setCellValue(text); |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | // 为每一列创建单独的工作表并写入非空数据 |
| 334 | for (int columnIndex = 0; columnIndex < table.getColumnCount(); columnIndex++) { |
| 335 | XSSFSheet sheet = workbook.createSheet(sanitizeSheetName(table.getColumnName(columnIndex))); |
| 336 | |
| 337 | // 创建表头 |
| 338 | XSSFRow columnHeaderRow = sheet.createRow(0); |
| 339 | columnHeaderRow.createCell(0).setCellValue(table.getColumnName(columnIndex)); |
| 340 | |
| 341 | // 写入该列的非空数据 |
| 342 | int dataRowIndex = 1; |
| 343 | for (int rowIndex = 0; rowIndex < table.getRowCount(); rowIndex++) { |
| 344 | Object value = table.getValueAt(rowIndex, columnIndex); |
| 345 | if (value != null) { |
| 346 | XSSFRow dataRow = sheet.createRow(dataRowIndex++); |
| 347 | dataRow.createCell(0).setCellValue(value.toString()); |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | // 将工作簿保存到文件 |
| 353 | try { |
| 354 | SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss"); |
| 355 | String timestamp = dateFormat.format(new Date()); |
| 356 | |
| 357 | String directoryName = "exportdata"; |
| 358 | File directory = new File(directoryName); |
| 359 | |
| 360 | if (!directory.exists()) { |
| 361 | directory.mkdirs(); // Use mkdirs() instead of mkdir() to create any necessary parent directories |
| 362 | } |
| 363 | |
| 364 | String fileName = directoryName + "/TableData_" + timestamp + ".xlsx"; |
| 365 | FileOutputStream output = new FileOutputStream(fileName); |
| 366 | workbook.write(output); |
| 367 | output.close(); // Close the file output stream |
| 368 | workbook.close(); // Close the workbook |
no test coverage detected