end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

apache poi for java による excel(xlsx)作成

過去、excel(xlsx)の読込や作成は、 perlpythonにて実施していますが、javaでもお試し。

参考url

インターネットで検索すると、上記の2番目が上位に表示されますが、 リファレンスとしては、少々、古いようですので、3番目を参照

apache poi 自体が扱いやすい構成ですので、以下のように書けば、OK

pom.xml

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

jp.end0tknr.XlsxOutService

package jp.end0tknr;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

@Service
public class XlsxOutService {

    public void outXlsx() {

        Workbook wBook = new XSSFWorkbook();  // for xlsx
        //Workbook wBook = new HSSFWorkbook(); // for xls

        Sheet wSheet = wBook.createSheet();

        // セルの書式の生成
        CellStyle cellStyle = wBook.createCellStyle();

        // フォント設定
        Font font = wBook.createFont();
        font.setFontName("MS ゴシック");
        font.setFontHeightInPoints((short)12); // size
        font.setUnderline(Font.U_SINGLE);      //下線
        font.setBold(true);                    //太字
        cellStyle.setFont(font);

        // 枠線/罫線の表示
        cellStyle.setBorderBottom(BorderStyle.THIN);

        // セルの結合
        wSheet.addMergedRegion(new CellRangeAddress(2, 3, 2, 4)); //行x2 , 列x2


        // 罫線の表示/非表示
        //wSheet.setDisplayGridlines(false);

        Row  outRow = wSheet.createRow(0);
        Cell outCell = outRow.createCell(0);

        outCell.setCellStyle(cellStyle);
        outCell.setCellValue("POIからの出力値");

        // 行高さ 調整
        outRow.setHeightInPoints(2 * wSheet.getDefaultRowHeightInPoints() );
        // セル幅 調整
        wSheet.setColumnWidth(3, 1024); // 1文字分の幅=256
        // セル幅 自動調整
        wSheet.autoSizeColumn(0, true);


        FileOutputStream out;
        try {
            out = new FileOutputStream("./TEXT_POI.XLSX");
            wBook.write(out);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        } catch (IOException e) {
            // TODO 自動生成された catch ブロック
            e.printStackTrace();
            return;
        }
    }
}