内容
JavaでApache POIを使用してエクセル出力を行ったメモ。
主にセルのスタイル引継ぎメイン。
- 1セルのみ書式設定をセット
- A2からA6 同じワークブック
- A2からA6 同じワークブック セルスタイルの複製
- A2からA6 違うワークブック XSSFWorkbook
- A2からA6 違うワークブック Workbook
- A2からA6 同じワークブック A2書式引継ぎ
- A7からA10 同じワークブック A2書式引継ぎ
- A7からA10 同じワークブック セルスタイルの複製
- A7からA10 同じワークブック セルスタイルの複製2
- A7からA10 違うワークブック 左上引継ぎ
- 全般引継ぎ
1セルのみ書式設定をセット 違うワークブック間
動作の流れ
- テンプレートの
A1
セルを取得。 - 行またはセルが存在しない場合、
createRow()
またはcreateCell()
で新規作成。 - スタイルやデータをコピーして、新しいファイル(
output.xlsx
)に保存。
package com.example.POIExample2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class App {
public static void main(String[] args) {
try (FileInputStream templateFile = new FileInputStream("template.xlsx");
XSSFWorkbook templateWorkbook = new XSSFWorkbook(templateFile);
XSSFWorkbook outputWorkbook = new XSSFWorkbook()) {
// テンプレートのシートを取得
XSSFSheet templateSheet = templateWorkbook.getSheetAt(0);
// A1セルを取得または作成
Row templateRow = templateSheet.getRow(0);
if (templateRow == null) {
templateRow = templateSheet.createRow(0); // 行を作成
}
Cell templateCell = templateRow.getCell(0);
if (templateCell == null) {
templateCell = templateRow.createCell(0); // セルを作成
}
// 出力用のシートとセルを作成
XSSFSheet outputSheet = outputWorkbook.createSheet("Sheet1");
Row outputRow = outputSheet.createRow(0); // 1行目を作成
Cell outputCell = outputRow.createCell(0); // A1セルを作成
// テンプレートのスタイルをコピー
CellStyle newStyle = outputWorkbook.createCellStyle();
newStyle.cloneStyleFrom(templateCell.getCellStyle());
outputCell.setCellStyle(newStyle);
// データをコピー
switch (templateCell.getCellType()) {
case STRING:
outputCell.setCellValue(templateCell.getStringCellValue());
break;
case NUMERIC:
outputCell.setCellValue(templateCell.getNumericCellValue());
break;
case BOOLEAN:
outputCell.setCellValue(templateCell.getBooleanCellValue());
break;
case FORMULA:
outputCell.setCellFormula(templateCell.getCellFormula());
break;
case BLANK:
outputCell.setBlank();
break;
default:
break;
}
// ファイルを出力
try (FileOutputStream outputStream = new FileOutputStream("output.xlsx")) {
outputWorkbook.write(outputStream);
}
System.out.println("A1セルの書式とデータを引き継ぎました。");
} catch (IOException e) {
e.printStackTrace();
}
}
}
A2からA6
セルの結合、罫線含め、何もしなくても引き継いでる
ただしセルのスタイルは引き継ぐ必要がある。
サンプルコード
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelTemplateHandler {
public static void main(String[] args) {
String inputFilePath = "template.xlsx"; // テンプレートファイルのパス
String outputFilePath = "output.xlsx"; // 出力ファイルのパス
try (FileInputStream fis = new FileInputStream(inputFilePath);
Workbook workbook = new XSSFWorkbook(fis)) {
// テンプレートの最初のシートを取得
Sheet sheet = workbook.getSheetAt(0);
// A2からA6まで任意の値を設定し、書式を引き継ぐ
for (int rowNum = 1; rowNum <= 5; rowNum++) { // A2 -> row 1 (0-based index)
Row row = sheet.getRow(rowNum);
if (row == null) {
row = sheet.createRow(rowNum);
}
Cell cell = row.getCell(0); // A列 = 列インデックス0
if (cell == null) {
cell = row.createCell(0);
}
// セルのスタイルを引き継ぐ
CellStyle originalStyle = cell.getCellStyle();
cell.setCellStyle(originalStyle);
// 任意の値をセット
cell.setCellValue("任意の値 " + rowNum);
}
// ファイルに書き込み
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
workbook.write(fos);
}
System.out.println("Excelファイルが出力されました: " + outputFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
A2からA6 同じワークブック セルスタイルの複製
package com.example.POIExample2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
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.XSSFWorkbook;
public class App {
public static void main(String[] args) {
String inputFilePath = "template.xlsx"; // テンプレートファイルのパス
String outputFilePath = "output.xlsx"; // 出力ファイルのパス
try (FileInputStream fis = new FileInputStream(inputFilePath);
Workbook workbook = new XSSFWorkbook(fis)) {
// テンプレートの最初のシートを取得
Sheet sheet = workbook.getSheetAt(0);
// A2からA6まで任意の値を設定し、各行のセルのスタイルをコピーして適用
for (int rowNum = 1; rowNum <= 5; rowNum++) { // A2 -> row 1 (0-based index)
Row row = sheet.getRow(rowNum);
if (row == null) {
throw new RuntimeException("テンプレートの行が存在しません: 行番号 " + (rowNum + 1));
}
Cell templateCell = row.getCell(0); // A列のセルを基準とする
if (templateCell == null) {
throw new RuntimeException("テンプレートのセルが存在しません: 行番号 " + (rowNum + 1));
}
// 各行のセルスタイルを基準にコピー
CellStyle templateStyle = templateCell.getCellStyle();
CellStyle sharedStyle = copyCellStyle(templateStyle, workbook, workbook);
// 行の作成(または取得)
Row newRow = sheet.getRow(rowNum);
if (newRow == null) {
newRow = sheet.createRow(rowNum);
}
// セルの作成(または取得)
Cell newCell = newRow.getCell(0);
if (newCell == null) {
newCell = newRow.createCell(0);
}
// コピーしたスタイルを適用
newCell.setCellStyle(sharedStyle);
// 任意の値をセット
newCell.setCellValue("任意の値 " + rowNum);
}
// ファイルに書き込み
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
workbook.write(fos);
}
System.out.println("Excelファイルが出力されました: " + outputFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
// セルスタイルをコピーするメソッド
private static CellStyle copyCellStyle(CellStyle originalStyle, Workbook templateWorkbook, Workbook newWorkbook) {
CellStyle newStyle = newWorkbook.createCellStyle();
// 各種プロパティのコピー
newStyle.setAlignment(originalStyle.getAlignment());
newStyle.setVerticalAlignment(originalStyle.getVerticalAlignment());
newStyle.setBorderTop(originalStyle.getBorderTop());
newStyle.setBorderBottom(originalStyle.getBorderBottom());
newStyle.setBorderLeft(originalStyle.getBorderLeft());
newStyle.setBorderRight(originalStyle.getBorderRight());
newStyle.setTopBorderColor(originalStyle.getTopBorderColor());
newStyle.setBottomBorderColor(originalStyle.getBottomBorderColor());
newStyle.setLeftBorderColor(originalStyle.getLeftBorderColor());
newStyle.setRightBorderColor(originalStyle.getRightBorderColor());
newStyle.setWrapText(originalStyle.getWrapText());
newStyle.setFillForegroundColor(originalStyle.getFillForegroundColor());
newStyle.setFillPattern(originalStyle.getFillPattern());
newStyle.setDataFormat(originalStyle.getDataFormat());
// フォントをコピー
Font originalFont = templateWorkbook.getFontAt(originalStyle.getFontIndexAsInt());
Font newFont = newWorkbook.createFont();
newFont.setFontName(originalFont.getFontName()); // フォント名
newFont.setFontHeight(originalFont.getFontHeight()); // フォントサイズ
newFont.setBold(originalFont.getBold()); // 太字
newFont.setItalic(originalFont.getItalic()); // イタリック
newFont.setColor(originalFont.getColor()); // フォント色
newFont.setUnderline(originalFont.getUnderline()); // 下線
newFont.setStrikeout(originalFont.getStrikeout()); // 打ち消し線
newStyle.setFont(newFont);
return newStyle;
}
}
A7からA10 同じワークブック セルスタイルの複製2
package com.example.POIExample2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class App {
public static void main(String[] args) {
String inputFilePath = "template.xlsx"; // テンプレートファイルのパス
String outputFilePath = "output.xlsx"; // 出力ファイルのパス
try (FileInputStream fis = new FileInputStream(inputFilePath);
Workbook workbook = new XSSFWorkbook(fis)) {
// テンプレートの最初のシートを取得
Sheet sheet = workbook.getSheetAt(0);
// A2からA6まで任意の値を設定し、書式を引き継ぐ
for (int rowNum = 1; rowNum <= 5; rowNum++) { // A2 -> row 1 (0-based index)
Row row = sheet.getRow(rowNum);
if (row == null) {
row = sheet.createRow(rowNum);
}
Cell cell = row.getCell(0); // A列 = 列インデックス0
if (cell == null) {
cell = row.createCell(0);
}
// セルのスタイルを引き継ぐ
CellStyle newCellStyle = cell.getSheet().getWorkbook().createCellStyle();
newCellStyle.cloneStyleFrom(cell.getCellStyle());
cell.setCellStyle(newCellStyle);
// 任意の値をセット
cell.setCellValue("任意の値 " + rowNum);
}
// A7からA10のセルを結合し値をセットし罫線と書式を追加
for (int rowNum = 6; rowNum <= 9; rowNum++) { // A7 -> row 6 (0-based index)
Row row = sheet.getRow(rowNum);
if (row == null) {
row = sheet.createRow(rowNum);
}
// A列からE列を結合
CellRangeAddress cellRangeAddress = new CellRangeAddress(
rowNum, rowNum, 0, 4 // 行: rowNum, 列: A(0)〜E(4)
);
if (!isMergedRegion(sheet, cellRangeAddress)) {
sheet.addMergedRegion(cellRangeAddress); // 未結合なら結合を追加
}
// セルのスタイルを引き継ぐ
for (int colNum = 0; colNum <= 4; colNum++) {
// 左上セルのスタイル利用
Cell cell = row.getCell(colNum);
if(cell == null) {
cell = row.createCell(colNum);
}
// CellStyle originalStyle = cell.getCellStyle();s
// CellStyle sharedStyle = copyCellStyle(originalStyle, workbook, workbook);
// セルのスタイルをコピー
CellStyle newCellStyle = cell.getSheet().getWorkbook().createCellStyle();
newCellStyle.cloneStyleFrom(cell.getCellStyle());
// 罫線を設定
newCellStyle.setBorderTop(BorderStyle.THIN);
newCellStyle.setBorderBottom(BorderStyle.THIN);
newCellStyle.setBorderLeft(BorderStyle.THIN);
newCellStyle.setBorderRight(BorderStyle.THIN);
// 水平・垂直中央揃えを設定
newCellStyle.setAlignment(HorizontalAlignment.CENTER);
newCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cell.setCellStyle(newCellStyle);
cell.setCellValue("結合セルの値 " + (rowNum + 1));
}
}
// ファイルに書き込み
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
workbook.write(fos);
}
System.out.println("Excelファイルが出力されました: " + outputFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
// セル結合が既に存在するかをチェックするメソッド
private static boolean isMergedRegion(Sheet sheet, CellRangeAddress region) {
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress existingRegion = sheet.getMergedRegion(i);
if (existingRegion.getFirstRow() == region.getFirstRow() &&
existingRegion.getLastRow() == region.getLastRow() &&
existingRegion.getFirstColumn() == region.getFirstColumn() &&
existingRegion.getLastColumn() == region.getLastColumn()) {
return true; // 結合セルが既に存在
}
}
return false; // 結合セルは存在しない
}
}
A2からA6 違うワークブック XSSFWorkbook
違うワークブック間
セルの結合を引き継ぐ必要がある、そうしないと元シートが結合されていても、結合がされない。
セルの書式は先頭だけでなく、結合箇所にセルの書式を引き継ぐ必要がある。もとは左上でよい。
package com.example.POIExample2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class App {
public static void main(String[] args) throws IOException {
String templateFilePath = "template.xlsx"; // テンプレートファイルのパス
String outputFilePath = "output.xlsx"; // 出力ファイルのパス
// テンプレートの読み込み
try (FileInputStream templateStream = new FileInputStream(templateFilePath);
XSSFWorkbook templateWorkbook = new XSSFWorkbook(templateStream);
XSSFWorkbook newWorkbook = new XSSFWorkbook()) {
// テンプレートの最初のシートを取得
XSSFSheet templateSheet = templateWorkbook.getSheetAt(0);
// 新しいシートを作成
XSSFSheet newSheet = newWorkbook.createSheet("Sheet1");
// 結合セルを引き継ぐ
int numMergedRegions = templateSheet.getNumMergedRegions();
for (int i = 0; i < numMergedRegions; i++) {
CellRangeAddress region = templateSheet.getMergedRegion(i);
newSheet.addMergedRegion(region);
}
// A2からA6のセルをコピーして値をセット
for (int rowIndex = 1; rowIndex <= 5; rowIndex++) {
Row templateRow = templateSheet.getRow(rowIndex);
if (templateRow == null) continue;
Row newRow = newSheet.createRow(rowIndex);
for (int colNum = 0; colNum <= 4; colNum++) { // A列からE列
Cell templateCell = templateRow.getCell(colNum);
if (templateCell == null) continue;
Cell newCell = newRow.createCell(colNum);
// スタイルをコピー
CellStyle copiedStyle = copyCellStyle(templateCell.getCellStyle(), templateWorkbook, newWorkbook);
newCell.setCellStyle(copiedStyle);
// 左上セルのみに値を設定
if (colNum == 0) {
newCell.setCellValue("セルの値 " + (rowIndex + 1)); // 動的な値設定
}
}
}
// 出力
try (FileOutputStream outputStream = new FileOutputStream(outputFilePath)) {
newWorkbook.write(outputStream);
}
System.out.println("Excelファイルが出力されました: " + outputFilePath);
}
}
private static CellStyle copyCellStyle(CellStyle originalStyle, XSSFWorkbook templateWorkbook, XSSFWorkbook newWorkbook) {
CellStyle newStyle = newWorkbook.createCellStyle();
// 各種プロパティのコピー
newStyle.setAlignment(originalStyle.getAlignment());
newStyle.setVerticalAlignment(originalStyle.getVerticalAlignment());
newStyle.setBorderTop(originalStyle.getBorderTop());
newStyle.setBorderBottom(originalStyle.getBorderBottom());
newStyle.setBorderLeft(originalStyle.getBorderLeft());
newStyle.setBorderRight(originalStyle.getBorderRight());
newStyle.setTopBorderColor(originalStyle.getTopBorderColor());
newStyle.setBottomBorderColor(originalStyle.getBottomBorderColor());
newStyle.setLeftBorderColor(originalStyle.getLeftBorderColor());
newStyle.setRightBorderColor(originalStyle.getRightBorderColor());
newStyle.setWrapText(originalStyle.getWrapText());
newStyle.setFillForegroundColor(originalStyle.getFillForegroundColor());
newStyle.setFillBackgroundColor(originalStyle.getFillBackgroundColor());
newStyle.setFillPattern(originalStyle.getFillPattern());
newStyle.setRotation(originalStyle.getRotation());
newStyle.setIndention(originalStyle.getIndention());
newStyle.setDataFormat(originalStyle.getDataFormat());
newStyle.setShrinkToFit(originalStyle.getShrinkToFit());
// フォントのコピー
Font originalFont = templateWorkbook.getFontAt(originalStyle.getFontIndexAsInt());
Font newFont = newWorkbook.createFont();
newFont.setFontName(originalFont.getFontName());
newFont.setFontHeight(originalFont.getFontHeight());
newFont.setBold(originalFont.getBold());
newFont.setItalic(originalFont.getItalic());
newFont.setColor(originalFont.getColor());
newFont.setUnderline(originalFont.getUnderline());
newFont.setStrikeout(originalFont.getStrikeout());
newStyle.setFont(newFont);
return newStyle;
}
}
コードの説明
-
テンプレートの読み込み:
-
template.xlsx
を読み込んでテンプレートのシートを取得します。
-
-
新しいシートの作成:
- 新しいシートにA2からA6のセルをコピーし、値を設定します。
-
copyCellStyle
の使用:- 指定された
CellStyle
をコピーし、新しいセルに適用します。
- 指定された
-
値の設定:
- 任意の値(例: "任意の値" + 行番号)を設定しています。
-
出力:
- 新しいExcelファイルとして保存します。
A2からA6 結合あり 違うワークブック間 Workbook
違うワークブック間はセルの結合設定が必要
package com.example.POIExample2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
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.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class App {
public static void main(String[] args) {
String inputFilePath = "template.xlsx"; // テンプレートファイルのパス
String outputFilePath = "output.xlsx"; // 出力ファイルのパス
try (FileInputStream fis = new FileInputStream(inputFilePath);
Workbook templateWorkbook = new XSSFWorkbook(fis);
Workbook newWorkbook = new XSSFWorkbook()) {
// テンプレートと新しいシートを取得
Sheet templateSheet = templateWorkbook.getSheetAt(0);
Sheet newSheet = newWorkbook.createSheet("Sheet1");
// 結合セルを引き継ぐ
List<CellRangeAddress> mergedRegions = templateSheet.getMergedRegions();
for (CellRangeAddress region : mergedRegions) {
newSheet.addMergedRegion(region);
}
// A2からA6のセルに値をセットし、それぞれの書式を引き継ぐ
for (int rowNum = 1; rowNum <= 5; rowNum++) { // A2 -> row 1 (0-based index)
Row templateRow = templateSheet.getRow(rowNum);
if (templateRow == null) continue;
Row newRow = newSheet.createRow(rowNum);
for (int colNum = 0; colNum <= 4; colNum++) { // A列からE列
Cell templateCell = templateRow.getCell(colNum);
if (templateCell == null) continue;
Cell newCell = newRow.createCell(colNum);
// スタイルをコピー
CellStyle copiedStyle = copyCellStyle(templateCell.getCellStyle(), templateWorkbook, newWorkbook);
newCell.setCellStyle(copiedStyle);
// 左上セルのみに値を設定
if (colNum == 0) {
newCell.setCellValue("セルの値 " + (rowNum + 1)); // 動的な値設定
}
}
}
// ファイルを書き込み
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
newWorkbook.write(fos);
}
System.out.println("Excelファイルが出力されました: " + outputFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
// セルスタイルをコピーするメソッド
private static CellStyle copyCellStyle(CellStyle originalStyle, Workbook templateWorkbook, Workbook newWorkbook) {
CellStyle newStyle = newWorkbook.createCellStyle();
// 各種プロパティのコピー
newStyle.setAlignment(originalStyle.getAlignment());
newStyle.setVerticalAlignment(originalStyle.getVerticalAlignment());
newStyle.setBorderTop(originalStyle.getBorderTop());
newStyle.setBorderBottom(originalStyle.getBorderBottom());
newStyle.setBorderLeft(originalStyle.getBorderLeft());
newStyle.setBorderRight(originalStyle.getBorderRight());
newStyle.setTopBorderColor(originalStyle.getTopBorderColor());
newStyle.setBottomBorderColor(originalStyle.getBottomBorderColor());
newStyle.setLeftBorderColor(originalStyle.getLeftBorderColor());
newStyle.setRightBorderColor(originalStyle.getRightBorderColor());
newStyle.setWrapText(originalStyle.getWrapText());
newStyle.setFillForegroundColor(originalStyle.getFillForegroundColor());
newStyle.setFillPattern(originalStyle.getFillPattern());
newStyle.setDataFormat(originalStyle.getDataFormat());
// フォントをコピー
Font originalFont = templateWorkbook.getFontAt(originalStyle.getFontIndexAsInt());
Font newFont = newWorkbook.createFont();
newFont.setFontName(originalFont.getFontName());
newFont.setFontHeight(originalFont.getFontHeight());
newFont.setBold(originalFont.getBold());
newFont.setItalic(originalFont.getItalic());
newFont.setColor(originalFont.getColor());
newFont.setUnderline(originalFont.getUnderline());
newFont.setStrikeout(originalFont.getStrikeout());
newStyle.setFont(newFont);
return newStyle;
}
}
A2からA6(A2のセル書式を引き継ぐ) 同じワークブック
package com.example.POIExample2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
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.XSSFWorkbook;
public class App {
public static void main(String[] args) {
String inputFilePath = "template.xlsx"; // テンプレートファイルのパス
String outputFilePath = "output.xlsx"; // 出力ファイルのパス
try (FileInputStream fis = new FileInputStream(inputFilePath);
Workbook workbook = new XSSFWorkbook(fis)) {
// シートを取得
Sheet sheet = workbook.getSheetAt(0);
// A2の書式を取得
Row templateRow = sheet.getRow(1); // A2 -> row 1 (0-based index)
if (templateRow == null) {
throw new RuntimeException("テンプレートの行が存在しません。");
}
CellStyle templateStyle = templateRow.getCell(0).getCellStyle(); // A2の書式
// A2からA6に値をセット
for (int rowNum = 1; rowNum <= 5; rowNum++) { // A2 -> row 1 (0-based index)
Row row = sheet.getRow(rowNum);
if (row == null) {
row = sheet.createRow(rowNum);
}
Cell cell = row.getCell(0); // A列
if (cell == null) {
cell = row.createCell(0);
}
// 書式を設定
cell.setCellStyle(templateStyle);
// 値をセット
cell.setCellValue("セルの値 " + (rowNum + 1));
}
// ファイルを書き込み
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
workbook.write(fos);
}
System.out.println("Excelファイルが出力されました: " + outputFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
A7からA10(A2のセル書式を引き継ぐ) 結合 同じワークブック
package com.example.POIExample2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
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.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class App {
public static void main(String[] args) {
String inputFilePath = "template.xlsx"; // テンプレートファイルのパス
String outputFilePath = "output.xlsx"; // 出力ファイルのパス
try (FileInputStream fis = new FileInputStream(inputFilePath);
Workbook workbook = new XSSFWorkbook(fis)) {
// シートを取得
Sheet sheet = workbook.getSheetAt(0);
// A2の書式を取得
Row templateRow = sheet.getRow(1); // A2 -> row 1 (0-based index)
if (templateRow == null) {
throw new RuntimeException("テンプレートの行が存在しません。");
}
CellStyle templateStyle = templateRow.getCell(0).getCellStyle(); // A2の書式
// A7からA10のセルを結合し値をセットし罫線と書式を追加
for (int rowNum = 6; rowNum <= 9; rowNum++) { // A7 -> row 6 (0-based index)
Row row = sheet.getRow(rowNum);
if (row == null) {
row = sheet.createRow(rowNum);
}
// A列からE列を結合
CellRangeAddress cellRangeAddress = new CellRangeAddress(
rowNum, rowNum, 0, 4 // 行: rowNum, 列: A(0)〜E(4)
);
sheet.addMergedRegion(cellRangeAddress);
// 左上セルに値をセット
Cell cell = row.createCell(0);
cell.setCellStyle(templateStyle);
cell.setCellValue("結合セルの値 " + (rowNum + 1));
// 結合範囲内の罫線を設定
for (int colNum = 0; colNum <= 4; colNum++) {
Cell mergedCell = row.getCell(colNum);
if (mergedCell == null) {
mergedCell = row.createCell(colNum);
}
mergedCell.setCellStyle(templateStyle);
}
}
// ファイルを書き込み
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
workbook.write(fos);
}
System.out.println("Excelファイルが出力されました: " + outputFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
A7からA10 同じワークブック セルスタイルの複製
package com.example.POIExample2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class App {
public static void main(String[] args) {
String inputFilePath = "template.xlsx"; // テンプレートファイルのパス
String outputFilePath = "output.xlsx"; // 出力ファイルのパス
try (FileInputStream fis = new FileInputStream(inputFilePath);
Workbook workbook = new XSSFWorkbook(fis)) {
// テンプレートの最初のシートを取得
Sheet sheet = workbook.getSheetAt(0);
// A2からA6まで任意の値を設定し、書式を引き継ぐ
for (int rowNum = 1; rowNum <= 5; rowNum++) { // A2 -> row 1 (0-based index)
Row row = sheet.getRow(rowNum);
if (row == null) {
row = sheet.createRow(rowNum);
}
Cell cell = row.getCell(0); // A列 = 列インデックス0
if (cell == null) {
cell = row.createCell(0);
}
// セルのスタイルを引き継ぐ
CellStyle originalStyle = cell.getCellStyle();
CellStyle sharedStyle = copyCellStyle(originalStyle, workbook, workbook);
// 任意の値をセット
cell.setCellValue("任意の値 " + rowNum);
}
// A7からA10のセルを結合し値をセットし罫線と書式を追加
for (int rowNum = 6; rowNum <= 9; rowNum++) { // A7 -> row 6 (0-based index)
Row row = sheet.getRow(rowNum);
if (row == null) {
row = sheet.createRow(rowNum);
}
// A列からE列を結合
CellRangeAddress cellRangeAddress = new CellRangeAddress(
rowNum, rowNum, 0, 4 // 行: rowNum, 列: A(0)〜E(4)
);
if (!isMergedRegion(sheet, cellRangeAddress)) {
sheet.addMergedRegion(cellRangeAddress); // 未結合なら結合を追加
}
// セルのスタイルを引き継ぐ
for (int colNum = 0; colNum <= 4; colNum++) {
// 左上セルのスタイル利用
Cell cell = row.getCell(colNum);
if(cell == null) {
cell = row.createCell(colNum);
}
CellStyle originalStyle = cell.getCellStyle();
CellStyle sharedStyle = copyCellStyle(originalStyle, workbook, workbook);
// 罫線を設定
sharedStyle.setBorderTop(BorderStyle.THIN);
sharedStyle.setBorderBottom(BorderStyle.THIN);
sharedStyle.setBorderLeft(BorderStyle.THIN);
sharedStyle.setBorderRight(BorderStyle.THIN);
// 水平・垂直中央揃えを設定
sharedStyle.setAlignment(HorizontalAlignment.CENTER);
sharedStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cell.setCellStyle(sharedStyle);
cell.setCellValue("結合セルの値 " + (rowNum + 1));
}
}
// ファイルに書き込み
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
workbook.write(fos);
}
System.out.println("Excelファイルが出力されました: " + outputFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
// セル結合が既に存在するかをチェックするメソッド
private static boolean isMergedRegion(Sheet sheet, CellRangeAddress region) {
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress existingRegion = sheet.getMergedRegion(i);
if (existingRegion.getFirstRow() == region.getFirstRow() &&
existingRegion.getLastRow() == region.getLastRow() &&
existingRegion.getFirstColumn() == region.getFirstColumn() &&
existingRegion.getLastColumn() == region.getLastColumn()) {
return true; // 結合セルが既に存在
}
}
return false; // 結合セルは存在しない
}
// セルスタイルをコピーするメソッド
private static CellStyle copyCellStyle(CellStyle originalStyle, Workbook templateWorkbook, Workbook newWorkbook) {
CellStyle newStyle = newWorkbook.createCellStyle();
// 各種プロパティのコピー
newStyle.setAlignment(originalStyle.getAlignment());
newStyle.setVerticalAlignment(originalStyle.getVerticalAlignment());
newStyle.setBorderTop(originalStyle.getBorderTop());
newStyle.setBorderBottom(originalStyle.getBorderBottom());
newStyle.setBorderLeft(originalStyle.getBorderLeft());
newStyle.setBorderRight(originalStyle.getBorderRight());
newStyle.setTopBorderColor(originalStyle.getTopBorderColor());
newStyle.setBottomBorderColor(originalStyle.getBottomBorderColor());
newStyle.setLeftBorderColor(originalStyle.getLeftBorderColor());
newStyle.setRightBorderColor(originalStyle.getRightBorderColor());
newStyle.setWrapText(originalStyle.getWrapText());
newStyle.setFillForegroundColor(originalStyle.getFillForegroundColor());
newStyle.setFillPattern(originalStyle.getFillPattern());
newStyle.setDataFormat(originalStyle.getDataFormat());
// フォントをコピー
Font originalFont = templateWorkbook.getFontAt(originalStyle.getFontIndexAsInt());
Font newFont = newWorkbook.createFont();
newFont.setFontName(originalFont.getFontName()); // フォント名
newFont.setFontHeight(originalFont.getFontHeight()); // フォントサイズ
newFont.setBold(originalFont.getBold()); // 太字
newFont.setItalic(originalFont.getItalic()); // イタリック
newFont.setColor(originalFont.getColor()); // フォント色
newFont.setUnderline(originalFont.getUnderline()); // 下線
newFont.setStrikeout(originalFont.getStrikeout()); // 打ち消し線
newStyle.setFont(newFont);
return newStyle;
}
}
A7からA10 違うワークブック 左上の書式
output.xlsx
package com.example.POIExample2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class App {
public static void main(String[] args) {
String inputFilePath = "template.xlsx"; // テンプレートファイルのパス
String outputFilePath = "output.xlsx"; // 出力ファイルのパス
try (FileInputStream fis = new FileInputStream(inputFilePath);
Workbook templateWorkbook = new XSSFWorkbook(fis);
Workbook newWorkbook = new XSSFWorkbook()) {
// テンプレートシートと新しいシートを取得
Sheet templateSheet = templateWorkbook.getSheetAt(0);
Sheet newSheet = newWorkbook.createSheet("Sheet1");
// 結合セルを引き継ぐ
List<CellRangeAddress> mergedRegions = templateSheet.getMergedRegions();
for (CellRangeAddress region : mergedRegions) {
// 新しいシートに同じ範囲でセル結合を追加
CellRangeAddress newRegion = new CellRangeAddress(
region.getFirstRow(), region.getLastRow(),
region.getFirstColumn(), region.getLastColumn()
);
newSheet.addMergedRegion(newRegion);
}
// A2からA6のセルをコピー(例として)
for (int rowNum = 1; rowNum <= 5; rowNum++) { // A2 -> row 1 (0-based index)
Row templateRow = templateSheet.getRow(rowNum);
if (templateRow == null) continue;
Row newRow = newSheet.createRow(rowNum);
for (int colNum = 0; colNum <= 4; colNum++) { // A列からE列
Cell templateCell = templateRow.getCell(colNum);
if (templateCell == null) continue;
Cell newCell = newRow.createCell(colNum);
// スタイルをコピー
CellStyle copiedStyle = copyCellStyle(templateCell.getCellStyle(), templateWorkbook, newWorkbook);
newCell.setCellStyle(copiedStyle);
// テンプレートの値をコピー(必要なら)
if (templateCell.getCellType() == CellType.STRING) {
newCell.setCellValue(templateCell.getStringCellValue());
} else if (templateCell.getCellType() == CellType.NUMERIC) {
newCell.setCellValue(templateCell.getNumericCellValue());
}
}
}
// A7からA10までセルの結合、書式の引き継ぎ、値の設定
for (int rowNum = 6; rowNum <= 9; rowNum++) { // A7 -> row 6 (0-based index)
Row templateRow = templateSheet.getRow(rowNum);
if (templateRow == null) continue;
Row newRow = newSheet.createRow(rowNum);
// 左上セル(A列)の書式を基準にする
Cell templateCell = templateRow.getCell(0);
if (templateCell != null) {
CellStyle copiedStyle = copyCellStyle(templateCell.getCellStyle(), templateWorkbook, newWorkbook);
// 罫線を設定
copiedStyle.setBorderTop(BorderStyle.THIN);
copiedStyle.setBorderBottom(BorderStyle.THIN);
copiedStyle.setBorderLeft(BorderStyle.THIN);
copiedStyle.setBorderRight(BorderStyle.THIN);
// 水平・垂直中央揃えを設定
copiedStyle.setAlignment(HorizontalAlignment.CENTER);
copiedStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 結合セル全体(A列からE列)に適用
for (int colNum = 0; colNum <= 4; colNum++) { // A列からE列
Cell newCell = newRow.createCell(colNum);
newCell.setCellStyle(copiedStyle); // 左上セルのスタイルを適用
}
// セルの結合 (A列からE列)
CellRangeAddress mergedRegion = new CellRangeAddress(rowNum, rowNum, 0, 4);
newSheet.addMergedRegion(mergedRegion);
// 左上セルに値を設定
newRow.getCell(0).setCellValue("行 " + (rowNum + 1) + " の値");
}
}
// ファイルを書き込み
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
newWorkbook.write(fos);
}
System.out.println("Excelファイルが出力されました: " + outputFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
// セルスタイルをコピーするメソッド
private static CellStyle copyCellStyle(CellStyle originalStyle, Workbook templateWorkbook, Workbook newWorkbook) {
CellStyle newStyle = newWorkbook.createCellStyle();
// 各種プロパティのコピー
newStyle.setAlignment(originalStyle.getAlignment());
newStyle.setVerticalAlignment(originalStyle.getVerticalAlignment());
newStyle.setBorderTop(originalStyle.getBorderTop());
newStyle.setBorderBottom(originalStyle.getBorderBottom());
newStyle.setBorderLeft(originalStyle.getBorderLeft());
newStyle.setBorderRight(originalStyle.getBorderRight());
newStyle.setTopBorderColor(originalStyle.getTopBorderColor());
newStyle.setBottomBorderColor(originalStyle.getBottomBorderColor());
newStyle.setLeftBorderColor(originalStyle.getLeftBorderColor());
newStyle.setRightBorderColor(originalStyle.getRightBorderColor());
newStyle.setWrapText(originalStyle.getWrapText());
newStyle.setFillForegroundColor(originalStyle.getFillForegroundColor());
newStyle.setFillPattern(originalStyle.getFillPattern());
newStyle.setDataFormat(originalStyle.getDataFormat());
// フォントをコピー
Font originalFont = templateWorkbook.getFontAt(originalStyle.getFontIndexAsInt());
Font newFont = newWorkbook.createFont();
newFont.setFontName(originalFont.getFontName()); // フォント名
newFont.setFontHeight(originalFont.getFontHeight()); // フォントサイズ
newFont.setBold(originalFont.getBold()); // 太字
newFont.setItalic(originalFont.getItalic()); // イタリック
newFont.setColor(originalFont.getColor()); // フォント色
newFont.setUnderline(originalFont.getUnderline()); // 下線
newFont.setStrikeout(originalFont.getStrikeout()); // 打ち消し線
newStyle.setFont(newFont);
// デバッグ用: フォント情報を出力
// System.out.println("Font Name: " + originalFont.getFontName());
// System.out.println("Font Height: " + originalFont.getFontHeight());
// System.out.println("Font Bold: " + originalFont.getBold());
// System.out.println("Font Italic: " + originalFont.getItalic());
// System.out.println("Font Color: " + originalFont.getColor());
// System.out.println("Font Underline: " + originalFont.getUnderline());
// System.out.println("Font Strikeout: " + originalFont.getStrikeout());
return newStyle;
}
}
全般引継ぎ
package com.example.POIExample2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class App {
public static void main(String[] args) throws IOException {
String templateFilePath = "template.xlsx"; // テンプレートファイルのパス
String outputFilePath = "output.xlsx"; // 出力ファイルのパス
// テンプレートの読み込み
try (FileInputStream templateStream = new FileInputStream(templateFilePath);
XSSFWorkbook templateWorkbook = new XSSFWorkbook(templateStream);
XSSFWorkbook newWorkbook = new XSSFWorkbook()) {
// テンプレートの最初のシートを取得
XSSFSheet templateSheet = templateWorkbook.getSheetAt(0);
// 新しいシートを作成
XSSFSheet newSheet = newWorkbook.createSheet("Sheet1");
// 結合セルを引き継ぐ
int numMergedRegions = templateSheet.getNumMergedRegions();
for (int i = 0; i < numMergedRegions; i++) {
CellRangeAddress region = templateSheet.getMergedRegion(i);
newSheet.addMergedRegion(region);
// 結合セル用のスタイルを1回作成
XSSFCellStyle mergedCellStyle = newWorkbook.createCellStyle();
mergedCellStyle.cloneStyleFrom(templateSheet.getRow(region.getFirstRow())
.getCell(region.getFirstColumn())
.getCellStyle());
// 結合セル内の各セルに同じスタイルを適用
for (int row = region.getFirstRow(); row <= region.getLastRow(); row++) {
XSSFRow newRow = newSheet.getRow(row);
if (newRow == null) {
newRow = newSheet.createRow(row); // 行が存在しない場合は新しく作成
}
for (int col = region.getFirstColumn(); col <= region.getLastColumn(); col++) {
XSSFCell newCell = newRow.getCell(col);
if (newCell == null) {
newCell = newRow.createCell(col); // セルが存在しない場合は新しく作成
}
newCell.setCellStyle(mergedCellStyle); // 既存のスタイルを適用
}
}
}
// 元のシートの全セルを新しいシートにコピー
for (int rowIndex = 0; rowIndex <= templateSheet.getLastRowNum(); rowIndex++) {
XSSFRow templateRow = templateSheet.getRow(rowIndex);
if (templateRow == null) continue;
XSSFRow newRow = newSheet.createRow(rowIndex);
newRow.setHeight(templateRow.getHeight()); // 行の高さを設定
for (int colIndex = 0; colIndex < templateRow.getLastCellNum(); colIndex++) {
XSSFCell templateCell = templateRow.getCell(colIndex);
if (templateCell == null) continue;
XSSFCell newCell = newRow.createCell(colIndex);
// セルの値をコピー
switch (templateCell.getCellType()) {
case STRING:
newCell.setCellValue(templateCell.getStringCellValue());
break;
case NUMERIC:
newCell.setCellValue(templateCell.getNumericCellValue());
break;
case BOOLEAN:
newCell.setCellValue(templateCell.getBooleanCellValue());
break;
case FORMULA:
newCell.setCellFormula(templateCell.getCellFormula());
break;
default:
break;
}
// セルスタイルをコピー
CellStyle newCellStyle = copyCellStyle(templateCell.getCellStyle(), templateWorkbook, newWorkbook);
newCell.setCellStyle(newCellStyle);
}
}
// 列幅のコピー
for (int colIndex = 0; colIndex < templateSheet.getRow(0).getLastCellNum(); colIndex++) {
newSheet.setColumnWidth(colIndex, templateSheet.getColumnWidth(colIndex));
}
// 行の高さを正確にコピー
for (int rowIndex = 0; rowIndex <= templateSheet.getLastRowNum(); rowIndex++) {
XSSFRow templateRow = templateSheet.getRow(rowIndex);
if (templateRow != null) {
XSSFRow newRow = newSheet.getRow(rowIndex);
if (newRow == null) {
newRow = newSheet.createRow(rowIndex);
}
newRow.setHeight(templateRow.getHeight()); // 行の高さをコピー
}
}
// 出力
try (FileOutputStream outputStream = new FileOutputStream(outputFilePath)) {
newWorkbook.write(outputStream);
}
System.out.println("Excelファイルが出力されました: " + outputFilePath);
}
}
private static CellStyle copyCellStyle(CellStyle originalStyle, XSSFWorkbook templateWorkbook, XSSFWorkbook newWorkbook) {
CellStyle newStyle = newWorkbook.createCellStyle();
// 各種プロパティのコピー
newStyle.setAlignment(originalStyle.getAlignment());
newStyle.setVerticalAlignment(originalStyle.getVerticalAlignment());
newStyle.setBorderTop(originalStyle.getBorderTop());
newStyle.setBorderBottom(originalStyle.getBorderBottom());
newStyle.setBorderLeft(originalStyle.getBorderLeft());
newStyle.setBorderRight(originalStyle.getBorderRight());
newStyle.setTopBorderColor(originalStyle.getTopBorderColor());
newStyle.setBottomBorderColor(originalStyle.getBottomBorderColor());
newStyle.setLeftBorderColor(originalStyle.getLeftBorderColor());
newStyle.setRightBorderColor(originalStyle.getRightBorderColor());
newStyle.setWrapText(originalStyle.getWrapText());
newStyle.setFillForegroundColor(originalStyle.getFillForegroundColor());
newStyle.setFillBackgroundColor(originalStyle.getFillBackgroundColor());
newStyle.setFillPattern(originalStyle.getFillPattern());
newStyle.setRotation(originalStyle.getRotation());
newStyle.setIndention(originalStyle.getIndention());
newStyle.setDataFormat(originalStyle.getDataFormat());
newStyle.setShrinkToFit(originalStyle.getShrinkToFit());
// フォントのコピー
Font originalFont = templateWorkbook.getFontAt(originalStyle.getFontIndexAsInt());
Font newFont = newWorkbook.createFont();
newFont.setFontName(originalFont.getFontName());
newFont.setFontHeight(originalFont.getFontHeight());
newFont.setBold(originalFont.getBold());
newFont.setItalic(originalFont.getItalic());
newFont.setColor(originalFont.getColor());
newFont.setUnderline(originalFont.getUnderline());
newFont.setStrikeout(originalFont.getStrikeout());
newStyle.setFont(newFont);
return newStyle;
}
}