LoginSignup
0
0

More than 3 years have passed since last update.

【Java】ApachePOIでExcelを出力する

Posted at

初めに

 yuji323です。今回の記事では、JavaのライブラリであるApachePOIを使ってExcelファイルを出力する方法について記事にします。

背景

 業務で必要にかられたので。あと調べても古い記事が多くてちょっと不安だったので。

環境

pom.xml
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.0</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.0</version>
</dependency>

作成パターン① -.xlsxファイルを新規作成する

Java上で新規に.xlsxファイルを作成します。コードは以下

class CreateNewFile{
    public static void main(String[] args){

        // 出力先ファイルパス
        String output = "C\\users\\user\Desktop\newFileFromOrigin.xlsx"

        // 各オブジェクト作成
        Workbook book = new XSSFWorkbook();
        Sheet sheet = book.getSheet(this.sheetName);
        Row row;
        Cell cell;

        // Excelに書き込み
        row = sheet.getRow(0);
        cell = row.getCell(0);
        cell.setCelValue("Hello POI")

        // 出力
        FileOutputStream fos = new FileOutputStream(fullDataExcelPath);
        book.write(fos);
        book.close();
        fos.close();
    }
}

作成パターン② -既存の.xlsxファイルをもとに作成する。

class CreateNewFile{
    public static void main(String[] args){

        // 入力ファイルパス
        String input = "C\\users\\user\Desktop\template.xlsx"

        // 元ファイル読み込み 
        Workbook book = WorkbookFactory.create(new FileInputStream(input));
        Sheet sheet = book.getSheetAt(0);
        Row row;
        Cell cell;

        // Excelに書き込み
        row = sheet.getRow(0);
        cell = row.getCell(0);
        cell.setCelValue("Hello POI")

        // 出力
        book.write(new FileOutputStream(fullDataExcelPath));
        book.close();
        fos.close();
    }
}

まとめ

・新規作成するとき:Workbook book = new XSSFWorkbook();
・元ファイルから作成するとき:Workbook book = WorkbookFactory.create(new FileInputStream("ファイルパス"));
でファイル作成できる。

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