1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CsvXlator - CSVファイルをExcelに変換するJavaライブラリの紹介

Posted at

はじめに

CSVファイルをExcelファイルに変換する必要性は、業務システムでよくある要件の一つです。今回は、この変換を簡単に実現できるJavaライブラリ「CsvXlator」を開発したので、その機能と使い方を紹介します。

特徴

  • CSVファイルをExcelファイル(.xlsx)に変換
  • ヘッダー行の自動認識とスタイル適用(グレー背景、太字、罫線)
  • カスタムCSV形式のサポート(区切り文字、引用符など)
  • 文字コードの指定が可能(UTF-8、Shift-JISなど)
  • 列幅の自動調整
  • ストリームからの読み込みをサポート
  • SLF4Jによるログ出力

要件

  • Java 21以上
  • Gradle 8.12.1以上

インストール方法

Gradle

repositories {
    maven {
        url = uri("https://maven.pkg.github.com/shizuya-aishima/csvxlator")
        credentials {
            username = project.findProperty("gpr.user") ?: System.getenv("USERNAME")
            password = project.findProperty("gpr.key") ?: System.getenv("TOKEN")
        }
    }
}
dependencies {
    implementation 'io.github.shizuya-aishima:csvxlator-core:0.1.0'
}

基本的な使用例

1. シンプルな変換(UTF-8、カンマ区切り)

import com.example.library.CsvToExcelConverter;
import java.io.File;
// デフォルト設定(RFC4180準拠、UTF-8)でコンバーターを作成
CsvToExcelConverter converter = new CsvToExcelConverter();
// CSVファイルをExcelに変換
File csvFile = new File("input.csv");
File excelFile = new File("output.xlsx");
converter.convert(csvFile, excelFile);

入力CSVファイル例(input.csv):

名前,年齢,都道府県
山田太郎,30,東京都
鈴木花子,25,大阪府

2. カスタム設定での使用(Shift-JIS、セミコロン区切り)

import org.apache.commons.csv.CSVFormat;
import java.nio.charset.Charset;
// カスタムCSV形式を指定
CSVFormat customFormat = CSVFormat.DEFAULT
.builder()
.setDelimiter(';') // セミコロン区切り
.setQuote('"') // ダブルクォートで囲む
.setHeader() // 1行目をヘッダーとして扱う
.build();
// Shift-JISでの読み込み
CsvToExcelConverter converter = new CsvToExcelConverter(
customFormat,
Charset.forName("SHIFT-JIS")
);
converter.convert(csvFile, excelFile);

生成されるExcelファイルの特徴

  • ヘッダー行のスタイル
    • 背景色: グレー(25%)
    • フォント: 太字
    • 罫線: 上下左右に細線
  • データ行
    • 自動的に列幅を調整
    • セル値は文字列として保存

エラーハンドリング

try {
converter.convert(csvFile, excelFile);
} catch (IOException e) {
// ファイルの読み書きエラー
logger.error("ファイルの処理中にエラーが発生しました: " + e.getMessage());
} catch (IllegalArgumentException e) {
// CSVフォーマットが不正
logger.error("不正なCSVフォーマット: " + e.getMessage());
}

ライセンス

MITライセンスで公開しています。商用利用も可能です。

ソースコード

GitHubで公開しています:
CsvXlator - GitHub

おわりに

CsvXlatorは、シンプルなAPIと柔軟なカスタマイズオプションを提供し、CSVからExcelへの変換を簡単に実現できるライブラリです。ぜひ使ってみてください。

フィードバックやプルリクエストも歓迎しています。

#Java #Excel #CSV #OSS

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?