- Home ›
- Apache POIでExcelを操作 ›
- シート ›
- HERE
指定の列の幅を設定
シートに含まれる特定の列の幅を設定する方法を確認します。幅を設定するにはSheetインターフェースで用意されているsetColumnWidthメソッドを使います。
setColumnWidth void setColumnWidth(int columnIndex, int width)
Set the width (in units of 1/256th of a character width) The maximum column width for an individual cell is 255 characters. This value represents the number of characters that can be displayed in a cell that is formatted with the standard font. Parameters: columnIndex - - the column to set (0-based) width - - the width in units of 1/256th of a character width
1番目の引数に列のインデックス、2番目の引数に列の幅を指定します。列のインデックスは一番左の列が0で順に1、2、と続きます。列の幅の指定方法は1文字の幅を1/256にしたものが単位となります。例えば1024を指定すると4文字分の幅に設定されます。
※フォントによっては文字の幅は文字によって異なりますが、どの文字を基準として計算しているかは分かりません。
実際の使い方は次のようになります。
InputStream in = new FileInputStream("filename.xls");
Workbook wb = WorkbookFactory.create(in);
Sheet sheet = wb.getSheetAt(0);
sheet.setColumnWidth(1, 4096);
この場合、インデックスが1の列の幅が16文字分の幅に設定されます。
なお指定の列の幅を取得するにはSheetインターフェースで用意されているgetColumnWidthメソッドを使います。
getColumnWidth int getColumnWidth(int columnIndex)
get the width (in units of 1/256th of a character width ) Parameters: columnIndex - - the column to set (0-based) Returns: width - the width in units of 1/256th of a character width
1番目の引数に列のインデックスを指定すると、その列の幅を返してくれます。単位は先ほどと同じです。
サンプルプログラム
実際に試してみましょう。
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import java.io.*;
public class Sample6_1{
public static void main(String[] args){
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet();
sheet.setColumnWidth(2, 4096);
sheet.setColumnWidth(3, 768);
FileOutputStream out = null;
try{
out = new FileOutputStream("sample6_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());
}
}
}
}
コンパイル後に実行するとシートのインデックス2の列の幅を16文字分の幅に設定し、インデックス3の列の幅を3文字分の幅に設定します。それでは作成されたファイルをExcelで開いてみます。
インデックス2の列とインデックス3の列の幅が変更されていることが確認できます。
( Written by Tatsuo Ikura )
JavaDrive