Spire.XLS for Java機能が豊富なエクセルのセットです,JavaアプリケーションでExcelファイルの作成、編集、変換、印刷をサポートします。本論文では、Spire.XLS for Javaを使ってExcelファイルを作成し、データを追加する方法を紹介します。
使用ツール:Free Spire.XLS for Java (無料版)
Jarファイルの取得と導入:
Method 1:ホームページを通じてjarファイルのカバンをダウンロードします。ダウンロード後、ファイルを解凍して、libフォルダの下のSpire.xls.jarファイルをJavaプログラムに導入します。
Method 2:maven倉庫設置による導入。
import com.spire.xls.*;
import java.awt.*;
public class CreateExcel {
public static void main(String[] args){
//新しいWorkbookの実例
Workbook workbook = new Workbook();
//最初のシートを取得します。(新しいWorkbookはデフォルトではシートが3つあります)
Worksheet sheet = workbook.getWorksheets().get(0);
//最初のシートの名前を設定します
sheet.setName("Data Sheet");
// 列の最初のセルスタイルを作成します
CellStyle style1 = workbook.getStyles().addStyle("Header Style");
style1.getFont().setSize(12f);
style1.getFont().setColor(Color.BLACK);
style1.getFont().isBold(true);
style1.setHorizontalAlignment(HorizontalAlignType.Center);
style1.setVerticalAlignment(VerticalAlignType.Center);
//データセルのスタイルを設定
CellStyle style2 = workbook.getStyles().addStyle("Data Style");
style2.getFont().setSize(10f);
style2.getFont().setColor(Color.BLACK);
//列の先頭セルにデータを追加し、スタイルを適用します
for (int column=1; column<5; column++)
{
CellRange header =sheet.getCellRange(1,column);
header.setValue("Column " + column );
header.setStyle(style1);
header.setColumnWidth(15f);
}
//データセルにデータを追加し、スタイルを適用します
for (int row=2; row<11; row++)
{
for (int column=1; column<5; column++)
{
CellRange cell = sheet.getCellRange(row, column);
cell.setValue("Data " + row + ", " + column);
cell.setStyle(style2);
}
}
//結果ファイルを保存
workbook.saveToFile("CreateExcel.xlsx", FileFormat.Version2013);
}
}