package poi; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; /** * ワークブックの読み込みサンプル */ public class HSSFReadSample { public static void main(String args[]) throws Exception { // (1)ワークブックの読み込み FileInputStream fis = new FileInputStream("./output/売上一覧.xls"); POIFSFileSystem poiFS = new POIFSFileSystem(fis); HSSFWorkbook workbook = new HSSFWorkbook(poiFS); // (2)セルスタイルの作成 HSSFCellStyle numericCellStyle = workbook.createCellStyle(); numericCellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); numericCellStyle.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index); numericCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); numericCellStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT); numericCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); numericCellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); numericCellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); numericCellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0")); // (3)シートの取得 HSSFSheet sheet = workbook.getSheetAt(0); // 開始・終了の行番号を取得する int firstRowNum = sheet.getFirstRowNum(); int lastRowNum = sheet.getLastRowNum(); for (int rowCnt = firstRowNum; rowCnt <= lastRowNum; rowCnt++) { // (4)行の取得 HSSFRow row = sheet.getRow(rowCnt); if (row != null) { // (5)セルの取得 HSSFCell cell = row.getCell((short) 5); if (cell != null && cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { double numeric = cell.getNumericCellValue(); // (6)新たなセルスタイルの設定 if (numeric >= 5000000) { cell.setCellStyle(numericCellStyle); } } } } FileOutputStream fos = new FileOutputStream("./output/売上一覧_1.xls"); workbook.write(fos); fis.close(); fos.close(); } }