10
10

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 5 years have passed since last update.

C# OpenXMLを使ってExcelを作成

Last updated at Posted at 2018-09-06

OpenXMLを使ってExcelを簡易的に作成できるライブラリを作ってみました。

ソースコード

以下のサイトからダウンロードしてください。
https://github.com/yunomichawan/SimpleExcelXml

このライブラリではDocumentFormat.OpenXmlを使用しています。

使い方

ファイル作成(新規作成、テンプレート使用)

ファイル作成、保存操作を実装
ファイル作成はStreamを経由して行われています。

Program.cs
// 新規のExcelファイルを作成
SimpleExcelCreator simpleExcelCreator = new SimpleExcelCreator("test.xlsx");

// テンプレートとなるExcelを基にファイル作成
SimpleExcelCreator simpleExcelCreator = new SimpleExcelCreator("template.xlsx", "use_template.xlsx");

// 保存
simpleExcelCreator.Save();

*新規作成時はシートが存在しないため手動で追加してください。

シート操作

基本的なシート操作を実装

// シート追加
simpleExcelCreator.AddSheet("SampleSheet1");
// シート選択
simpleExcelCreator.SelectSheet("SampleSheet2");
// 選択中のシート名変更
simpleExcelCreator.SetSheetName("ChangeName");
// シートの削除
simpleExcelCreator.RemoveSheet("SampleSheet3");

セル操作

データ書込

座標指定とセル指定でデータを書き込む処理を実装

// アルファベットとy座標でデータ書込
simpleExcelCreator.WriteCell("A", 1, 1000);
// x,y座標指定でデータ書込(0は範囲外になります)
simpleExcelCreator.WriteCell(1, 1, "temp");
// セル指定でデータ書込
simpleExcelCreator.WriteCell("A2", "temp");

行のコピペ

コピーした行のペースト、コピーした行の挿入を実装

/// <summary>
/// 行コピー&ペースト
/// </summary>
/// <param name="from">コピー元となる行数</param>
/// <param name="to">ペースト先の行数</param>
/// <param name="isInsert">挿入(true),ペースト(false)</param>
/// <param name="isDeep">コピーの深度</param>
public void RowCopyPaste(uint from, uint to, bool isInsert, bool isDeep = true)

// 行のコピー&ペースト
simpleExcelCreator.RowCopyPaste(2, 5, false);
// コピーした行を挿入
simpleExcelCreator.RowCopyPaste(2, 5, true);

オブジェクトの書込

クラスに実装されているプロパティを基に値を各セルに出力
セルに出力するプロパティにはCell属性を付与してください。

simpleExcelCreator.WriteDataObject(this.GetSample());

private ExcelSampleObject GetSample()
{
    ExcelSampleObject excelSampleObject = new ExcelSampleObject
    {
        CompanyName = "Sample会社",
        Name = "菓子",
        Price = 10000,
        Introduction = "お土産",
        Remarks = "複数箇所に出力",
        Excluded = "出力しないプロパティ"
    };

    return excelSampleObject;
}

/// <summary>
/// Sampleクラス
/// </summary>
public class ExcelSampleObject
{
    [Cell("{0}!", "A1")]
    public string Title
    {
        get
        {
            return this.CompanyName + " × " + this.Name;
        }
    }
   
    [Cell("A2")]
    public string CompanyName { get; set; }
    
    [Cell("商品名:{0}", "B2")]
    public string Name { get; set; }
    
    [Cell("C2")]
    public int Price { get; set; }
    
    [Cell("D2")]
    public string Introduction { get; set; }
    
    [Cell("", "E2", "E4")]
    public string Remarks { get; set; }

    /// <summary>
    /// 出力対象外のプロパティ
    /// Cell属性を適用していないプロパティは出力されません。
    /// </summary>
    public string Excluded { get; set; }
}

/// <summary>
/// プロパティに表示するセル位置を文字列(A1等)で与える
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class CellAttribute : Attribute
{
    /// <summary>
    /// セルの座標群
    /// </summary>
    public string[] Positions { get; set; }

    /// <summary>
    /// 出力フォーマット
    /// </summary>
    public string Format { get; set; }

    /// <summary>
    /// コンストラクタ
    /// </summary>
    /// <param name="format">出力フォーマット</param>
    /// <param name="positions">座標群</param>
    public CellAttribute(string format, params string[] positions)
    {
        this.Positions = positions;
        this.Format = format;
    }

    /// <summary>
    /// コンストラクタ
    /// </summary>
    /// <param name="position">座標</param>
    public CellAttribute(string position)
    {
        this.Positions = new string[] { position };
    }
}

注意

セルの書式設定に関する関数は一切実装していないため、自前で実装する必要があります。(気が向いたら実装するかもしれません...)

最後に

できるだけ簡単に操作できることをコンセプトに作ってみましたので使ってみてください!
ただ一部不自由なところがあり使いにくいところもあると思います。
そんな時は改造するなりしてみください。

不明な点、バグ等ありましたらツッコミください。
すぐに反応できるかはあやしいですが。。

10
10
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
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?