[Java] Apache POIでエクセルファイル(.xls)を出力する

1 min read

単純に、呼び出されたら hogehoge というシートを持った hoge.xls が出力されるだけです。

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  Workbook wb          = new HSSFWorkbook();
  Sheet sheet1         = wb.createSheet("hogehoge");
  FileOutputStream out = null;
  String fileName      = "hoge.xls";

  try {
    out = new FileOutputStream(fileName);
    wb.write(out);

  } catch (IOException e) {
    System.out.println(e.toString());

  } finally {
    try {
      out.close();

    } catch (IOException e) {
      System.out.println(e.toString());

    }
  }

  res.setContentType("application/octet-stream");
  res.setHeader("Content-Disposition", "attachment; filename="+ fileName);
  res.setHeader("Content-Description", "file download");
  res.setContentType("application/vnd.ms-excel");

  wb.write(res.getOutputStream());
}