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

Apache POI 操作 Excel 完全指南(三):HPSF 進階與 Servlet 輸出 Excel 範例

     編輯:Java 相關知識

HPSF 進階用法補充

  • SummaryInformation 常用 Getter:getTitle()、getAuthor()、getCreateDateTime()、getCharCount()、getApplicationName() 等。
  • DocumentSummaryInformation:getCategory()、getMultimediaClipCount() 等。
  • 自定義屬性集:需使用 PropertySet 通用 API 遍歷 Property 數組,較複雜,參考官方 HOW-TO。

附錄:Servlet 動態生成並下載 Excel

public class HSSFCreate extends HttpServlet {
    protected void processRequest(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("application/vnd.ms-excel");
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("new sheet");
        HSSFRow row = sheet.createRow((short)0);
        row.createCell((short)0).setCellValue(1);
        row.createCell((short)1).setCellValue(1.2);
        row.createCell((short)2).setCellValue("字符串值");
        row.createCell((short)3).setCellValue(true);

        OutputStream out = resp.getOutputStream();
        wb.write(out);
        out.close();
    }
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }
    public String getServletInfo() { return "Servlet 動態生成 Excel 示例"; }
}

部署提示

  • 在 web.xml 映射 Servlet 路徑(如 /export.xls)。
  • 瀏覽器訪問該 URL 將直接觸發下載或在線打開(取決於瀏覽器設置)。
  • 大數據量時建議使用 SXSSFWorkbook (POI 3.8+) 流式寫入,避免 OOM。

系列總結

三篇文章涵蓋:Usermodel 易用讀寫、Eventusermodel 高性能流式讀取、HPSF 文檔屬性讀取、Servlet 動態輸出。POI 功能強大,更多特性(圖表、樞紐分析、XML 轉 Excel)待開發者深入探索。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved