萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 動態生成 Word、Excel、PDF 文檔:Content-Type 設置與主流庫實戰對比

核心原理:MIME 類型驅動瀏覽器行為

瀏覽器根據 Content-Type 決定如何處理響應:內嵌顯示、觸發下載、或啟動關聯應用程序。

格式Content-Type副檔名Content-Disposition 範例
Wordapplication/msword.docattachment; filename="report.doc"
Word (OOXML)application/vnd.openxmlformats-officedocument.wordprocessingml.document.docxattachment; filename="report.docx"
Excelapplication/vnd.ms-excel.xlsattachment; filename="data.xls"
Excel (OOXML)application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.xlsxattachment; filename="data.xlsx"
PDFapplication/pdf.pdfinline; filename="doc.pdf" (預覽) / attachment (下載)

方案一:簡單 HTML 偽裝(僅適用極簡場景)

<%@ page contentType="application/msword;charset=UTF-8" %>
<% response.setHeader("Content-Disposition", "attachment; filename=export.doc"); %>
<html><body>
<h1><%= title %></h1>
<table border="1"><tr><th>欄位1</th><th>欄位2</th></tr>
<% for (Item item : list) { %>
  <tr><td><%= item.getCol1() %></td><td><%= item.getCol2() %></td></tr>
<% } %>
</table>
</body></html>

缺點:Office 會嘗試解析 HTML,複雜樣式/圖片/分頁失效,兼容性差。

方案二:Apache POI 生成真正的 Office 文件(推薦)

依賴

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>5.3.0</version>
</dependency>

生成 .xlsx 範例

<%@ page import="org.apache.poi.xssf.usermodel.*, org.apache.poi.ss.usermodel.*, java.io.*, java.util.*" %>
<%
  response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("報表.xlsx", "UTF-8"));

  Workbook wb = new XSSFWorkbook();
  Sheet sheet = wb.createSheet("數據");
  Row header = sheet.createRow(0);
  String[] cols = {"ID", "姓名", "金額", "日期"};
  for (int i = 0; i < cols.length; i++) header.createCell(i).setCellValue(cols[i]);

  // 假設從資料庫查詢
  List data = getDataFromDB(); 
  int rowIdx = 1;
  for (Object[] rowData : data) {
      Row row = sheet.createRow(rowIdx++);
      for (int i = 0; i < rowData.length; i++) row.createCell(i).setCellValue(String.valueOf(rowData[i]));
  }

  wb.write(response.getOutputStream());
  wb.close();
%>

生成 .docx 範例

XWPFDocument doc = new XWPFDocument();
doc.createParagraph().createRun().setText("標題: " + title);
XWPFTable table = doc.createTable(data.size()+1, cols.length);
// 填充表頭與數據...
doc.write(response.getOutputStream());
doc.close();

方案三:iText / OpenPDF 生成專業 PDF

依賴 (OpenPDF - LGPL/MPL,iText 7 需商業授權)

<dependency>
  <groupId>com.github.librepdf</groupId>
  <artifactId>openpdf</artifactId>
  <version>1.3.36</version>
</dependency>

PDF 生成範例

<%@ page import="com.lowagie.text.*, com.lowagie.text.pdf.*, java.io.*, java.awt.Color" %>
<%
  response.setContentType("application/pdf");
  response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode("報表.pdf", "UTF-8"));

  Document document = new Document(PageSize.A4.rotate());
  PdfWriter.getInstance(document, response.getOutputStream());
  document.open();

  // 中文字體(需註冊 TTF)
  BaseFont bfChinese = BaseFont.createFont("c:/windows/fonts/msjh.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
  Font font = new Font(bfChinese, 12);

  document.add(new Paragraph("銷售報表", new Font(bfChinese, 18, Font.BOLD)));
  document.add(new Paragraph("生成時間: " + new java.util.Date(), font));

  PdfPTable table = new PdfPTable(4);
  table.setWidths(new float[]{1, 3, 2, 2});
  for (String h : new String[]{"編號", "商品", "單價", "數量"}) {
      table.addCell(new PdfPCell(new Phrase(h, font)).setBackgroundColor(Color.LIGHT_GRAY));
  }
  for (Object[] row : getDataFromDB()) {
      for (Object cell : row) table.addCell(new Phrase(String.valueOf(cell), font));
  }
  document.add(table);
  document.close();
%>

方案四:JSP 模板 + 飛騰/騰訊文檔/OnlyOffice 在線轉換(企業級)

前端生成 HTML → 後端調用 LibreOffice Headless / 商業轉換服務 → 返回 PDF/Word → 下載。適合複雜排版、印章、簽章需求。

選型建議

場景推薦方案
簡單表格導出、內部工具POI (XLSX) / 簡單 HTML 偽裝
複雜報表、樣式、圖表、分頁POI + 樣式 API / 模板填充
正式合同、發票、需精準排版OpenPDF / iText / 商業轉換服務
大數據量導出(>10萬行)POI SXSSF (流式) / CSV / 分批次生成 ZIP

通用最佳實踐

  • 輸出流直接寫入 response.getOutputStream(),避免臨時文件
  • 文件名 URLEncoder.encode(filename, "UTF-8") 處理中文
  • 大文件設置 response.setBufferSize(65536) 減少 flush 次數
  • 生成邏輯移出 JSP,封裝至 Service/Controller,JSP 僅觸發
copyright © 萬盛學電腦網 all rights reserved