回転角度

広告

セルの中で値が表示される角度をスタイルに設定する方法を確認します。

回転角度を設定するにはCellStyleインターフェースで用意されているsetRotationメソッドを使います。

set the degree of rotation for the text in the cell

Parameters:
  rotation - degrees (between -90 and 90 degrees)

引数には角度を表すshort型の値を指定します。指定可能な値は -90 から 90 までの値です。

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

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

CellStyle  style = wb.createCellStyle();
style.setRotation((short)45);

この場合は、45度傾いた形で値が表示されます。

サンプルプログラム

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

Sample9_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 Sample9_1{
  public static void main(String[] args){
    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet();

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

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

    CellStyle style0 = wb.createCellStyle();
    style0.setRotation((short)45);
    cell[0].setCellStyle(style0);

    CellStyle style1 = wb.createCellStyle();
    style1.setRotation((short)0);
    cell[1].setCellStyle(style1);

    CellStyle style2 = wb.createCellStyle();
    style2.setRotation((short)-45);
    cell[2].setCellStyle(style2);

    CellStyle style3 = wb.createCellStyle();
    style3.setRotation((short)-90);
    cell[3].setCellStyle(style3);

    FileOutputStream out = null;
    try{
      out = new FileOutputStream("sample9_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());
      }
    }
  }
}

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

回転角度

指定した回転角度に応じて、値が傾いて表示されていることが確認できます。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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