Java生成格式化的Word統(tǒng)計報告
本教程將詳細介紹如何使用Java從數據庫查詢圖書數據,并生成格式化的Word統(tǒng)計報告。我們將使用Spring Boot框架和Apache POI庫來實現(xiàn)這一功能。
一、項目結構
src/main/java
├── com/example/libraryreport
│ ├── controller
│ │ └── ReportController.java
│ ├── service
│ │ └── BookReportService.java
│ ├── mapper
│ │ └── BookReportMapper.java
│ └── LibraryReportApplication.java
二、核心代碼實現(xiàn)
1. 控制器層
@RestController @RequestMapping("/api/reports") public class ReportController { @Autowired private BookReportService bookReportService; @GetMapping("/books") public ResponseEntity<String> generateBookReport() { try { String fileName = "圖書統(tǒng)計報告_" + System.currentTimeMillis() + ".docx"; String outputPath = "reports/" + fileName; bookReportService.generateReport(outputPath); return ResponseEntity.ok("報告生成成功: " + outputPath); } catch (Exception e) { return ResponseEntity.status(500) .body("報告生成失敗: " + e.getMessage()); } } }
2. 數據訪問層接口
public interface BookReportMapper { // 獲取圖書總量 int selectTotalBookCount(); // 按分類統(tǒng)計圖書數量 List<Map<String, Object>> selectBooksByCategory(); // 獲取熱門圖書TOP10 List<Map<String, Object>> selectPopularBooks(); // 獲取借閱統(tǒng)計 List<Map<String, Object>> selectBorrowStats(); }
3. 服務層實現(xiàn)
@Service public class BookReportService { @Autowired private BookReportMapper bookReportMapper; public void generateReport(String outputPath) throws Exception { // 創(chuàng)建Word文檔 XWPFDocument document = new XWPFDocument(); try { // 添加報告標題 addTitle(document, "圖書館圖書統(tǒng)計報告"); // 添加生成日期 addGenerationDate(document); // 添加圖書總量統(tǒng)計 addTotalBookCount(document); // 添加分類統(tǒng)計表格 addCategoryStatistics(document); // 添加熱門圖書列表 addPopularBooks(document); // 添加借閱統(tǒng)計 addBorrowStatistics(document); // 保存文檔 saveDocument(document, outputPath); } finally { document.close(); } } // 創(chuàng)建報告主標題,設置居中、加粗和大號字體 private void addTitle(XWPFDocument document, String titleText) { XWPFParagraph title = document.createParagraph(); title.setAlignment(ParagraphAlignment.CENTER); XWPFRun titleRun = title.createRun(); titleRun.setText(titleText); titleRun.setBold(true); titleRun.setFontSize(20); titleRun.setFontFamily("宋體"); // 添加空行 document.createParagraph(); } // 在右上角添加報告生成日期 private void addGenerationDate(XWPFDocument document) { XWPFParagraph datePara = document.createParagraph(); datePara.setAlignment(ParagraphAlignment.RIGHT); XWPFRun dateRun = datePara.createRun(); dateRun.setText("生成日期: " + LocalDate.now().toString()); dateRun.setFontSize(12); dateRun.setFontFamily("宋體"); // 添加空行 document.createParagraph(); } // 顯示圖書館藏書總量 private void addTotalBookCount(XWPFDocument document) { int totalCount = bookReportMapper.selectTotalBookCount(); XWPFParagraph sectionTitle = createSectionTitle(document, "一、圖書總量統(tǒng)計"); XWPFParagraph content = document.createParagraph(); XWPFRun run = content.createRun(); run.setText(String.format("圖書館目前共有藏書: %s冊", formatNumber(totalCount))); run.setFontSize(14); run.setFontFamily("宋體"); // 添加空行 document.createParagraph(); } // 創(chuàng)建分類統(tǒng)計表格,包括序號、分類名稱、數量和占比 private void addCategoryStatistics(XWPFDocument document) throws Exception { // 創(chuàng)建章節(jié)標題 XWPFParagraph sectionTitle = createSectionTitle(document, "二、圖書分類統(tǒng)計"); // 獲取分類數據 List<Map<String, Object>> categories = bookReportMapper.selectBooksByCategory(); int total = bookReportMapper.selectTotalBookCount(); // 創(chuàng)建表格 XWPFTable table = document.createTable(1, 4); table.setWidth("100%"); // 設置表頭 setTableHeader(table, "序號", "圖書分類", "數量", "占比"); // 填充數據 int index = 1; for (Map<String, Object> category : categories) { XWPFTableRow row = table.createRow(); row.getCell(0).setText(String.valueOf(index++)); row.getCell(1).setText(category.get("categoryName").toString()); int count = Integer.parseInt(category.get("count").toString()); row.getCell(2).setText(formatNumber(count)); double percent = (count * 100.0) / total; row.getCell(3).setText(String.format("%.1f%%", percent)); } // 添加匯總行 XWPFTableRow footer = table.createRow(); footer.getCell(1).setText("總計"); footer.getCell(2).setText(formatNumber(total)); footer.getCell(3).setText("100%"); // 添加空行 document.createParagraph(); } // 列出熱門圖書TOP10,前三名用藍色加粗顯示 private void addPopularBooks(XWPFDocument document) { // 創(chuàng)建章節(jié)標題 XWPFParagraph sectionTitle = createSectionTitle(document, "三、熱門圖書TOP10"); List<Map<String, Object>> popularBooks = bookReportMapper.selectPopularBooks(); for (int i = 0; i < popularBooks.size(); i++) { Map<String, Object> book = popularBooks.get(i); XWPFParagraph item = document.createParagraph(); item.setIndentationLeft(200); XWPFRun run = item.createRun(); run.setText(String.format("%d. 《%s》 - %s (借閱量: %s次)", i + 1, book.get("title"), book.get("author"), formatNumber(Long.parseLong(book.get("borrowCount").toString())) ); run.setFontSize(12); run.setFontFamily("宋體"); // 突出顯示前三名 if (i < 3) { run.setBold(true); run.setColor("0000FF"); } } // 添加空行 document.createParagraph(); } // 創(chuàng)建借閱統(tǒng)計表格,顯示每月借閱量和同比增長率 private void addBorrowStatistics(XWPFDocument document) { // 創(chuàng)建章節(jié)標題 XWPFParagraph sectionTitle = createSectionTitle(document, "四、借閱統(tǒng)計"); List<Map<String, Object>> borrowStats = bookReportMapper.selectBorrowStats(); // 創(chuàng)建表格 XWPFTable table = document.createTable(1, 3); table.setWidth("100%"); // 設置表頭 setTableHeader(table, "月份", "借閱量", "同比增長"); // 填充數據 for (Map<String, Object> stat : borrowStats) { XWPFTableRow row = table.createRow(); row.getCell(0).setText(stat.get("month").toString()); row.getCell(1).setText(formatNumber(Long.parseLong(stat.get("count").toString()))); // 計算同比增長 if (stat.containsKey("growthRate")) { double growth = Double.parseDouble(stat.get("growthRate").toString()); row.getCell(2).setText(String.format("%.1f%%", growth * 100)); // 設置顏色:增長為紅色,下降為綠色 XWPFRun growthRun = row.getCell(2).getParagraphs().get(0).getRuns().get(0); if (growth > 0) { growthRun.setColor("FF0000"); } else if (growth < 0) { growthRun.setColor("00FF00"); } } else { row.getCell(2).setText("N/A"); } } } // 輔助方法,創(chuàng)建統(tǒng)一的章節(jié)標題格式 private XWPFParagraph createSectionTitle(XWPFDocument document, String title) { XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText(title); run.setBold(true); run.setFontSize(16); run.setFontFamily("宋體"); return paragraph; } // 輔助方法,設置表格表頭樣式 private void setTableHeader(XWPFTable table, String... headers) { XWPFTableRow headerRow = table.getRow(0); for (int i = 0; i < headers.length; i++) { XWPFRun run = headerRow.getCell(i).getParagraphs().get(0).createRun(); run.setText(headers[i]); run.setBold(true); run.setFontSize(12); run.setFontFamily("宋體"); // 設置單元格背景色 headerRow.getCell(i).setColor("D3D3D3"); } } // 格式化數字顯示,添加千位分隔符 private String formatNumber(long number) { return String.format("%,d", number); } // 保存Word文檔到指定路徑 private void saveDocument(XWPFDocument document, String outputPath) throws IOException { // 確保目錄存在 File outputFile = new File(outputPath); outputFile.getParentFile().mkdirs(); try (FileOutputStream out = new FileOutputStream(outputFile)) { document.write(out); } } }
四、運行效果
文檔樣式細節(jié)
字體規(guī)范:
- 中文默認使用"宋體",數字/英文自動匹配
- 標題層級分明(20號→16號→14號→12號)
數字處理:
- 所有數量自動添加千位分隔符(如
1,200
) - 百分比保留1位小數(如
28.4%
)
- 所有數量自動添加千位分隔符(如
顏色標記:
- 藍色:TOP3熱門圖書
- 紅色/綠色:借閱量增長/下降
- 灰色:表格標題背景
布局設計:
- 章節(jié)間有適當空行
- 表格寬度占滿頁面(100%)
- 列表項統(tǒng)一縮進
數據完整性:
- 包含總量統(tǒng)計、分類占比、排行榜和趨勢分析
- 自動計算百分比和增長率
具體結果如下
+------------------------------------------+
| 圖書館圖書統(tǒng)計報告 |
| (大標題) |
| |
| 生成日期:2023-05-20 (右上角小字) |
| |
| 一、圖書總量統(tǒng)計 |
| 圖書館目前共有藏書:12,345冊 |
| |
| 二、圖書分類統(tǒng)計 |
| +----+------------+-------+-------+ |
| |序號| 圖書分類 | 數量 | 占比 | |
| +----+------------+-------+-------+ |
| |1 |計算機科學 | 3,500 | 28.4% | |
| |2 |文學 | 2,800 | 22.7% | |
| ... |
| | |總計 |12,345 | 100% | |
| +----+------------+-------+-------+ |
| |
| 三、熱門圖書TOP10 |
| 1. 《Java編程思想》...(藍色加粗) |
| 2. 《三體》...(藍色加粗) |
| ... |
| |
| 四、借閱統(tǒng)計 |
| +------------+--------+----------+ |
| | 月份 | 借閱量 | 同比增長 | |
| +------------+--------+----------+ |
| | 2023-01 | 1,200 | +15.2%↑ | |
| | 2023-02 | 980 | -8.3%↓ | |
| ... |
+-----------------------------------------+
五、總結
通過本教程,我們實現(xiàn)了:
- 使用Spring Boot構建Web服務
- 通過MyBatis訪問數據庫獲取統(tǒng)計信息
- 使用Apache POI生成格式化的Word文檔
- 實現(xiàn)表格、列表等復雜格式的輸出
這個方案可以輕松擴展為其他類型的統(tǒng)計報告生成工具,只需修改SQL查詢和Word格式設置即可。
到此這篇關于Java生成格式化的Word統(tǒng)計報告的文章就介紹到這了,更多相關Java生成Word內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
springboot利用aspose預覽office文件的實現(xiàn)過程
這篇文章主要給大家介紹了關于springboot利用aspose預覽office文件的相關資料,文中通過示例代碼以及圖文介紹的非常詳細,對大家的學習或者工作具有一定的參考價值,需要的朋友可以參考下2021-06-06