wrapの設定

広告

セルに設定された値がセルの幅に収まらない場合にどのように表示するのかを設定します。

warpの設定を行うにはにはCellStyleインターフェースで用意されているsetWrapTextメソッドを使います。

Set whether the text should be wrapped. Setting this flag to true make all content 
visible whithin a cell by displaying it on multiple lines 

Parameters:
  wrapped - wrap text or not

引数にはtrueを指定するとセル内で自動的に折り返しが行われ、複数の行に渡って値が表示されます。

実際の使い方は次のようになります。

Workbook wb = new HSSFWorkbook();
DataFormat format = wb.createDataFormat();

CellStyle  style = wb.createCellStyle();
style.setWrapText(true);

この場合は、4折り返しが行われます。

サンプルプログラム

実際に試してみましょう。

Sample10_1.java

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.*;

public class Sample10_1{
  public static void main(String[] args){
    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet();

    Row[] row = new Row[2];
    Cell[] cell = new Cell[2];

    for (int i = 0 ; i < 2 ; i++){
      row[i] = sheet.createRow(i + 1);
      cell[i] = row[i].createCell(2);
      cell[i].setCellValue("Thank you very much.");
    }

    CellStyle style0 = wb.createCellStyle();
    style0.setWrapText(true);
    cell[0].setCellStyle(style0);

    CellStyle style1 = wb.createCellStyle();
    style1.setWrapText(false);
    cell[1].setCellStyle(style1);

    FileOutputStream out = null;
    try{
      out = new FileOutputStream("sample10_1.xls");
      wb.write(out);
    }catch(IOException e){
      System.out.println(e.toString());
    }finally{
      try {
        out.close();
      }catch(IOException e){
        System.out.println(e.toString());
      }
    }
  }
}

各セルに対してwrapのスタイルを設定しています。それでは作成されたExcelファイルを開いてみます。

wrapの設定

wrapをtrueに設定した場合、値がセルに入りきらなかった時は、自動的に折り返しが行われて全体がセルの中に表示されます。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。