首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 整合 POI 與 Struts 2 實現 Excel 報表匯出功能

     編輯:Java 相關知識

整體流程

  1. Action 方法設定檔名編碼並回傳 success。
  2. getInputStream() 產生 Excel 二進位串流。
  3. struts.xml 配置 stream 結果型別,指定 MIME、檔名、串流來源。
  4. 前端按鈕直接連結 Action URL 觸發下載。

1. Action 類別

public class ActiveCountAction extends ActionSupport {
    private String fileName;
    private InputStream inputStream;

    public String exportActiveExcel() {
        String name = "活躍度列表.xls";
        try {
            name = URLEncoder.encode(name, "UTF-8");
            fileName = new String(name.getBytes(), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
        return SUCCESS;
    }

    public InputStream getInputStream() {
        ExportExcel ex = new ExportExcel();
        String[] headers = {"學號", "姓名", "年齡", "性別", "出生日期"};
        JSONArray data = new JSONArray();
        // 填充測試資料...
        return ex.exportExcel("活躍度分析", headers, data);
    }
    // getter/setter 略...
}

2. Excel 產生工具類

public class ExportExcel {
    public InputStream exportExcel(String title, String[] headers, JSONArray array) {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(title);
        sheet.setDefaultColumnWidth(30);

        // 樣式與字體設定略...

        // 標題列
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(titleStyle);
            cell.setCellValue(new HSSFRichTextString(headers[i]));
        }

        // 資料列
        for (int i = 0; i < array.size(); i++) {
            row = sheet.createRow(i + 1);
            JSONArray arr = array.getJSONArray(i);
            for (int j = 0; j < arr.size(); j++) {
                HSSFCell cell = row.createCell(j);
                cell.setCellStyle(contentStyle);
                HSSFRichTextString txt = new HSSFRichTextString(arr.get(j).toString());
                txt.applyFont(contentFont); // 藍色字體
                cell.setCellValue(txt);
            }
        }

        // 寫入 ByteArrayOutputStream
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        wb.write(baos);
        byte[] bytes = baos.toByteArray();
        try { baos.close(); } catch (IOException ignored) {}
        return new ByteArrayInputStream(bytes);
    }
}

3. struts.xml 配置


    
        application/vnd.ms-excel
        attachment;filename="${fileName}"
        inputStream
        4096
    

4. 前端呼叫


關鍵注意事項

  • inputName 對應 Action 的 getInputStream() 方法(去掉 get 首字小寫)。
  • 檔名編碼雙重處理(UTF-8 → ISO-8859-1)解決中文檔名亂碼。
  • 使用 ByteArrayInputStream 避免臨時檔案 I/O。
  • POI 版本需與專案相容,HSSF 為 .xls,XSSF 為 .xlsx。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved