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?

More than 3 years have passed since last update.

 Java   Excel ピボットテーブルを作成

Posted at

ピボットテーブルは表計算ソフトまたはビジネスインテリジェンスソフトウェアにて利用されるデータ可視化要約機能である。今日は Spire.XLS for Javaを使ってExcelでピボットテーブルを作成する方法を紹介します。

下準備

1.E-iceblueの公式サイトからFree Spire. XLS for Java無料版をダウンロードしてください。

f:id:lendoris:20210303151514p:plain 

2.IDEを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいSpire. XLS.jarを参照に追加してください。

f:id:lendoris:20210303151547p:plain

```JAVA

import com.spire.xls.*;

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

    Workbook workbook = new Workbook();
    workbook.loadFromFile("Sample.xlsx");

    Worksheet sheet = workbook.getWorksheets().get(0);

    //キャッシュを作成します。

     
CellRange dataRange = sheet.getCellRange("A1:C19");
PivotCache cache = workbook.getPivotCaches().add(dataRange);

    //キャッシュを使ってピボットテーブルして、テーブルの名前と位置を指定します。
    PivotTable pt = sheet.getPivotTables().add("Pivot Table", sheet.getCellRange("E10"), cache);

    // Rowを追加します。
    PivotField pf=null;
    if (pt.getPivotFields().get("Name") instanceof PivotField){
        pf= (PivotField) pt.getPivotFields().get("Name");
    }
    pf.setAxis(AxisTypes.Row);

    PivotField pf2 =null;
    if (pt.getPivotFields().get("Area") instanceof PivotField){
        pf2= (PivotField) pt.getPivotFields().get("Area");
    }
    pf2.setAxis(AxisTypes.Row);

    //值を追加します。
    pt.getDataFields().add(pt.getPivotFields().get("Population"), "SUM of Count", SubtotalTypes.Sum);

    //ピボットテーブルを書式設定します。
    pt.setBuiltInStyle(PivotBuiltInStyles.PivotStyleMedium12);

    //保存します。
    workbook.saveToFile("output/CreatePivotTable.xlsx", ExcelVersion.Version2013);
}

<h4><strong>実行結果</strong></h4>
<p><img src="https://cdn-ak.f.st-hatena.com/images/fotolife/l/lendoris/20210303/20210303151624.png" alt="f:id:lendoris:20210303151624p:plain" title="" class="hatena-fotolife" itemprop="image" /></p>
<p><strong> </strong></p>
<p><strong> </strong></p>
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?