欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java生成格式化的Word統(tǒng)計報告

 更新時間:2025年04月08日 08:45:45   作者:我是福福大王  
這篇文章主要為大家詳細介紹了如何使用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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 淺談MyBatis 如何執(zhí)行一條 SQL語句

    淺談MyBatis 如何執(zhí)行一條 SQL語句

    Mybatis 是 Java 開發(fā)中比較常用的 ORM 框架。在日常工作中,我們都是直接通過 Spring Boot 自動配置,并直接使用,但是卻不知道 Mybatis 是如何執(zhí)行一條 SQL 語句的,下面就一起講解一下
    2021-05-05
  • SpringBoot使用OpenCV示例總結

    SpringBoot使用OpenCV示例總結

    這篇文章主要介紹了SpringBoot使用OpenCV示例總結,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-08-08
  • 關于@Transactional事務嵌套使用方式

    關于@Transactional事務嵌套使用方式

    Spring框架通過@Transactional注解來管理事務,它可以作用于類和方法上,用于聲明事務的屬性,如傳播行為、隔離級別、超時時間等,Spring事務是基于AOP實現(xiàn)的,它在運行時為加了@Transactional注解的方法或類創(chuàng)建代理
    2024-11-11
  • java1.5中訪問環(huán)境變量

    java1.5中訪問環(huán)境變量

    這篇文章主要介紹了如何在java1.5中訪問環(huán)境變量,使用System.getenv()可以訪問環(huán)境變量
    2014-01-01
  • Java中while語句的簡單知識及應用

    Java中while語句的簡單知識及應用

    這篇文章主要給大家介紹了關于Java中while語句的簡單知識及應用的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-01-01
  • Java 中的偽共享詳解及解決方案

    Java 中的偽共享詳解及解決方案

    這篇文章主要介紹了Java 中的偽共享詳解及解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-02-02
  • java處理日期的工具類DateUtil

    java處理日期的工具類DateUtil

    這篇文章主要為大家詳細介紹了java處理日期的工具類DateUtil,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-10-10
  • Java實現(xiàn)的日期處理類完整實例

    Java實現(xiàn)的日期處理類完整實例

    這篇文章主要介紹了Java實現(xiàn)的日期處理類,結合完整實例形式分析了Java針對日期的獲取、運算、轉換等相關操作技巧,需要的朋友可以參考下
    2017-09-09
  • springboot利用aspose預覽office文件的實現(xiàn)過程

    springboot利用aspose預覽office文件的實現(xiàn)過程

    這篇文章主要給大家介紹了關于springboot利用aspose預覽office文件的相關資料,文中通過示例代碼以及圖文介紹的非常詳細,對大家的學習或者工作具有一定的參考價值,需要的朋友可以參考下
    2021-06-06
  • Java e.printStackTrace()案例講解

    Java e.printStackTrace()案例講解

    這篇文章主要介紹了Java e.printStackTrace()案例講解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下
    2021-08-08

最新評論