LoginSignup
9
18

More than 5 years have passed since last update.

Spring-bootへのApache Poiの導入 1(生成してコントローラから呼び出すまで)

Last updated at Posted at 2015-12-20

目的

Spring-bootにて、Excel帳票を出力する
今回は、とりあえずExcelファイルを生成し、コントローラから呼び出して出力を返す(ダウンロード)まで

次回は、既存のテンプレートへ記入してダウンロードする方法をまとめる。

環境

Spring-boot 1.3.1.RELEAS
java8
テンプレートエンジン Thymeleaf
IDE STS3.7.1
Apatch-Poi 3.13

手順

最終的なプロジェクトの構成
スクリーンショット 2015-12-20 13.14.34.png

pom への依存性の追加

pom.xml

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

以上の依存性を追加。
versionは、導入するPoiのバージョン
※実はここでむちゃくちゃハマった。
自分が持っていた環境に、poi関連のjarがなく、ビルドパスがはれなかった。
これについては後述する。

画面からのコントローラ操作

出力ボタンを配置する。

test.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>top page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
test
  <p th:text="${msg}" /> 
  <form th:action="@{/test/download}" method="post">
   <input class="btn btn-danger" type="submit" value="出力" />
</form>
</body>
</html>

出力ボタンが配置できた。
ここで、action属性に対して/test/downloadを呼び出し、postメソッドを使う
それを、コントローラで受けとる

Controller

package com.example.web;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.example.excelexport.ExcelBuilder;

@Controller
@RequestMapping("/test")
public class MainController {

    @RequestMapping(method = RequestMethod.GET)
    public String test(Model model) {
        model.addAttribute("msg","サンプルメッセージ!");
        return "test/test";
    }
    @RequestMapping(value = "download", method = RequestMethod.POST)
    public ModelAndView download(Map<String, Object> model) throws Exception {
        ModelAndView mav = new ModelAndView(new ExcelBuilder());

        mav.addObject("fileName", "testExcel" + ".xls");

        return mav;
    }

}

これの

抜粋
@RequestMapping(value = "download", method = RequestMethod.POST)
    public ModelAndView download(Map<String, Object> model) throws Exception {
        ModelAndView mav = new ModelAndView(new ExcelBuilder());

        mav.addObject("fileName", "testExcel" + ".xls");

        return mav;
    }

ModelAndViewクラスは、Springが用意してくれているクラス。
これに、 Excelを作って入れて返せばダウンロードとなる。

Excelの作成

フレームワークが用意しているpoi操作用の抽象クラス
AbstractExcelViewを継承する

出力するExcelの操作はここでする

ExcelBuilder
package com.example.excelexport;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

public class ExcelBuilder extends AbstractExcelView {

    @Override
    protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook wb, HttpServletRequest req,
            HttpServletResponse res) throws Exception {
        String fileName = new String("サンプル.xls".getBytes("MS932"), "ISO-8859-1");
        res.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        HSSFSheet sheet;
        HSSFCell cell;

        sheet = wb.createSheet("Spring");
        cell = getCell(sheet, 0, 0);
        setText(cell, "Spring-Excel test");

    }

}


まず、ComponentであることをComponentSchanに伝え
buildExcelDocumentを実装する
このなかで帳票の記入を行う
AbstructExcelViewを実装した帳票作成クラスは、コントローラから呼び出されると
buildExcelDocumentが呼び出される。帳票が作成される

トラブル

jarがない

Poiの導入(クラスパスを張る)
スクリーンショット 2015-12-13 13.03.24.png
画像はエラーが全て取れているが、poi関係のjarがmissingになっている。
それを、パスの指定のある箇所へ配置する。

http://poi.apache.org/download.html
Poiをダウンロードし解凍すると、以下のようになっており。
スクリーンショット 2015-12-13 13.15.05.png
これをビルドパスエラーの指摘通りに配置しするスクリーンショット 2015-12-13 13.11.03.png
例えばjarの配置場所はだいたい上のようになっており、
今回、新しく3.13バージョンのjarを追加するため、3.13フォルダを追加し、その中にjarを配置する

プロジェクトを更新して再ビルドするとjar missingエラーはとれた

・stax-api-1.0.1.jarがPOIに入ってない、別でダウンロードした
・poi-3.1334132.jarみたいにバージョン番号が入っているが、ビルドパスで登録されている通りの名前poi-3.13.jar等に直す

AbstractExcelViewの継承クラスが、poiのクラスインポートでエラーとなる

コントローラクラスと同じパッケージに配置していたため、うまくいかなかったらしい。
帳票出力を行うクラスのためのパッケージを用意し、そこへ配置しコントローラから呼び出すようにしたところ解消
それが、com.example.excelexportパッケージに相当する

課題

次回は、元から用意したExcelテンプレートを読みだしてきて記入する方法を見つける

参考

Spring bootでの帳票出力
http://blog.okazuki.jp/entry/2015/07/18/220959

Spring MVCからSpring Bootへ乗せ変える内容。Excel出力を行っている。
http://brissyu.blogspot.jp/2015/04/spring-boot-web.html
http://brissyu.blogspot.jp/2015/08/spring-boot-web.html

Spring MVCでのExcel出力
https://terasolunaorg.github.io/guideline/public_review/ArchitectureInDetail/FileDownload.html#viewresolver-label

9
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
18