0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[スニペット] Java8 ApchePOIでExcel1行目にフィルタを設定

Posted at
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelFilterSetter {

    public static void addFilterToFirstRow(String inputPath, String outputPath) throws IOException {
        try (FileInputStream fis = new FileInputStream(inputPath);
             Workbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheetAt(0); // 1枚目のシートを取得

            // 1行目のセル数(列数)を取得
            int lastColumn = sheet.getRow(0).getLastCellNum() - 1;

            if (lastColumn >= 0) {
                // フィルタの範囲を1行目に設定(例: A1〜C1)
                sheet.setAutoFilter(new CellRangeAddress(0, 0, 0, lastColumn));
            }

            // 保存
            try (FileOutputStream fos = new FileOutputStream(outputPath)) {
                workbook.write(fos);
            }
        }
    }
}
public class Main {
    public static void main(String[] args) {
        try {
            ExcelFilterSetter.addFilterToFirstRow("input.xlsx", "output.xlsx");
            System.out.println("フィルタを追加しました!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?