CellStyle#setAlignment(...)で横位置の設定、CellStyle#setVerticalAlignment(...)で縦位置の設定を行う。
値 |
横位置 |
ALIGN_CENTER |
中央揃え |
ALIGN_CENTER_SELECTION |
選択範囲内で中央 |
ALIGN_FILL |
繰り返す |
ALIGN_GENERAL |
標準 |
ALIGN_JUSTIFY |
両端揃え |
ALIGN_LEFT |
左寄せ |
ALIGN_RIGHT |
右寄せ |
値 |
縦位置 |
VERTICAL_BOTTOM |
下寄せ |
VERTICAL_CENTER |
中央揃え |
VERTICAL_JUSTIFY |
両端揃え |
VERTICAL_TOP |
上寄せ |
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
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.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class PoiAlignmentTest {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("POI Alignment Sheet");
Row row = sheet.createRow((short)0);
row.setHeightInPoints(50);
createCell(workbook, row, (short)0, XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_BOTTOM);
createCell(workbook, row, (short)1, XSSFCellStyle.ALIGN_CENTER_SELECTION, XSSFCellStyle.VERTICAL_BOTTOM);
createCell(workbook, row, (short)2, XSSFCellStyle.ALIGN_FILL, XSSFCellStyle.VERTICAL_CENTER);
createCell(workbook, row, (short)3, XSSFCellStyle.ALIGN_GENERAL, XSSFCellStyle.VERTICAL_CENTER);
createCell(workbook, row, (short)4, XSSFCellStyle.ALIGN_JUSTIFY, XSSFCellStyle.VERTICAL_JUSTIFY);
createCell(workbook, row, (short)5, XSSFCellStyle.ALIGN_LEFT, XSSFCellStyle.VERTICAL_TOP);
createCell(workbook, row, (short)6, XSSFCellStyle.ALIGN_RIGHT, XSSFCellStyle.VERTICAL_TOP);
FileOutputStream fileOut = new FileOutputStream("C:/workbookAlignment.xlsx");
workbook.write(fileOut);
fileOut.close();
}
セルの生成・要素の縦位置/横位置指定.
@param wb
@param row
@param column
@param hAlign
@param vAlign
private static void createCell(
Workbook wb,
Row row,
short column,
short hAlign,
short vAlign) {
Cell cell = row.createCell(column);
cell.setCellValue(new XSSFRichTextString("Align it."));
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(hAlign);
cellStyle.setVerticalAlignment(vAlign);
cell.setCellStyle(cellStyle);
}
}
実行結果。