EPPlusでファイル作成、保存方法

作成

ファイルパスを指定

Excelデータをメモリ上で作って、別名保存する場合(SaveAs)

using OfficeOpenXml;
using System;
using System.IO;
using System.Reflection;

namespace SampleCode
{
    internal class SampleEPPlus
    {
        static void Main(string[] args)
        {
            // Ver8.0のソースです
            // 非商用個人利用の場合 名前を設定
            ExcelPackage.License.SetNonCommercialPersonal("SampleTarou");

            try
            {
                // 実行ファイルのあるフォルダパス取得
                var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
                if (folderPath == null) { return; }

                // Excelファイルパスを作成
                var filePath = Path.Combine(folderPath, "sample.xlsx");

                // Excelデータと紐づける
                using (var package = new ExcelPackage())
                {
                    // シートを追加
                    var worksheet =  package.Workbook.Worksheets.Add("sample");

                    // A1形式
                    worksheet.Cells["A1"].Value = "A1";
                    
                    // 行列形式
                    worksheet.Cells[1, 2].Value = "B1";

                    // 上書き保存
                    package.SaveAs(filePath);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"エラー: {ex.Message}");
            }
        }
    }
}

※new FileInfo(filePath) としても同じ

保存先のファイルパスを含んだ状態で、Excelデータを作成し上書き保存する(Save)

using OfficeOpenXml;
using System;
using System.IO;
using System.Reflection;

namespace SampleCode
{
    internal class SampleEPPlus
    {
        static void Main(string[] args)
        {
            // Ver8.0のソースです
            // 非商用個人利用の場合 名前を設定
            ExcelPackage.License.SetNonCommercialPersonal("SampleTarou");

            try
            {
                // 実行ファイルのあるフォルダパス取得
                var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
                if (folderPath == null) { return; }

                // Excelファイルパスを作成
                var filePath = Path.Combine(folderPath, "sample.xlsx");

                // Excelデータと紐づける
                using (var package = new ExcelPackage(filePath))
                {
                    // シートを追加
                    var worksheet = package.Workbook.Worksheets.Add("sample");

                    // A1形式
                    worksheet.Cells["A1"].Value = "A1";

                    // 行列形式
                    worksheet.Cells[1, 2].Value = "B1";

                    // 上書き保存
                    package.Save();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"エラー: {ex.Message}");
            }
        }
    }
}

※new FileInfo(filePath) としても同じ結果

Streamを指定
using OfficeOpenXml;
using System;
using System.IO;
using System.IO.Pipes;
using System.Reflection;

namespace SampleCode
{
    internal class SampleEPPlus
    {
        static void Main(string[] args)
        {
            // Ver8.0のソースです
            // 非商用個人利用の場合 名前を設定
            ExcelPackage.License.SetNonCommercialPersonal("SampleTarou");

            try
            {
                // 実行ファイルのあるフォルダパス取得
                var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
                if (folderPath == null) { return; }

                // Excelファイルパスを作成
                var filePath = Path.Combine(folderPath, "sample.xlsx");

                using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
                using (var package = new ExcelPackage(stream))
                {
                    // シートを追加
                    var worksheet = package.Workbook.Worksheets.Add("sample");

                    // A1形式
                    worksheet.Cells["A1"].Value = "A1";

                    // 行列形式
                    worksheet.Cells[1, 2].Value = "B1";

                    // 上書き保存
                    package.Save();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"エラー: {ex.Message}");
            }
        }
    }
}

式を記載する場合の注意点

sumを記載し値を確認
using OfficeOpenXml;
using System;
using System.IO;
using System.Reflection;

namespace SampleCode
{
    internal class SampleEPPlus
    {
        static void Main(string[] args)
        {
            // Ver8.0のソースです
            // 非商用個人利用の場合 名前を設定
            ExcelPackage.License.SetNonCommercialPersonal("SampleTarou");

            try
            {
                // 実行ファイルのあるフォルダパス取得
                var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
                if (folderPath == null) { return; }

                // Excelファイルパスを作成
                var filePath = Path.Combine(folderPath, "sample.xlsx");

                using (var package = new ExcelPackage())
                {
                    // シートを追加
                    var worksheet =  package.Workbook.Worksheets.Add("sample");

                    for(var r = 1; r <=3; r++)
                    {
                        worksheet.Cells[r, 1].Value = 10 * r;
                    }

                    worksheet.Cells[4, 1].Formula = "sum(A1:A3)";

                    // 上書き保存
                    package.SaveAs(filePath);
                }

                // 開きなおす
                using (var package = new ExcelPackage(filePath))
                {
                    var worksheet = package.Workbook.Worksheets["sample"];

                    // 計算の結果を取得
                    var samValue = worksheet.Cells[4, 1].Value;
                    Console.WriteLine($"Sumの値は = {samValue}");

                    // 計算モードの取得
                    var calcMode = package.Workbook.CalcMode;
                    Console.WriteLine($"計算モード = {calcMode}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"エラー: {ex.Message}");
            }
        }
    }
}

実行結果は以下のとおりです。

Sumの値は =
計算モード = Automatic

60が返ってくることを期待していたのですが、ここでいう計算モードのAUtomaticは
Excelアプリケーションで開いたときの挙動であり、XMLを直接操作した場合の挙動とは無関係にないrます
そのため、プログラムを書く人が、明示的に

Workbook.Calculate() か Worksheet.Calculate()してあげる必要がある

using OfficeOpenXml;
using System;
using System.IO;
using System.Reflection;

namespace SampleCode
{
    internal class SampleEPPlus
    {
        static void Main(string[] args)
        {
            // Ver8.0のソースです
            // 非商用個人利用の場合 名前を設定
            ExcelPackage.License.SetNonCommercialPersonal("SampleTarou");

            try
            {
                // 実行ファイルのあるフォルダパス取得
                var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
                if (folderPath == null) { return; }

                // Excelファイルパスを作成
                var filePath = Path.Combine(folderPath, "sample.xlsx");

                using (var package = new ExcelPackage())
                {
                    // シートを追加
                    var worksheet =  package.Workbook.Worksheets.Add("sample");

                    for(var r = 1; r <=3; r++)
                    {
                        worksheet.Cells[r, 1].Value = 10 * r;
                    }

                    worksheet.Cells[4, 1].Formula = "sum(A1:A3)";

                    // 計算する
                    //package.Workbook.Calculate(); // ワークブック単位で計算
                    worksheet.Calculate();        // ワークシート単位で計算

                    // 上書き保存
                    package.SaveAs(filePath);
                }

                // 開きなおす
                using (var package = new ExcelPackage(filePath))
                {
                    var worksheet = package.Workbook.Worksheets["sample"];

                    // 計算の結果を取得
                    var samValue = worksheet.Cells[4, 1].Value;
                    Console.WriteLine($"Sumの値は = {samValue}");

                    // 計算モードの取得
                    var calcMode = package.Workbook.CalcMode;
                    Console.WriteLine($"計算モード = {calcMode}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"エラー: {ex.Message}");
            }
        }
    }
}

上書き保存

ファイルパスを指定
using OfficeOpenXml;
using System;
using System.IO;
using System.Reflection;

namespace SampleCode
{
    internal class SampleEPPlus
    {
        static void Main(string[] args)
        {
            // Ver8.0のソースです
            // 非商用個人利用の場合 名前を設定
            ExcelPackage.License.SetNonCommercialPersonal("SampleTarou");

            try
            {
                // 実行ファイルのあるフォルダパス取得
                var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
                if (folderPath == null) { return; }

                // Excelファイルパスを作成
                var filePath = Path.Combine(folderPath, "sample.xlsx");

                // ファイルを開く
                using (var package = new ExcelPackage(filePath))
                {
                    // 最初のシートを取得
                    var worksheet = package.Workbook.Worksheets[0]; 
                    worksheet.Cells["A1"].Value = DateTime.Now.ToString("HH:mm:ss");
                
                    // 上書き保存
                    package.Save();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"エラー: {ex.Message}");
            }
        }
    }
}
streamを指定
using OfficeOpenXml;
using System;
using System.IO;
using System.IO.Pipes;
using System.Reflection;

namespace SampleCode
{
    internal class SampleEPPlus
    {
        static void Main(string[] args)
        {
            // Ver8.0のソースです
            // 非商用個人利用の場合 名前を設定
            ExcelPackage.License.SetNonCommercialPersonal("SampleTarou");

            try
            {
                // 実行ファイルのあるフォルダパス取得
                var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
                if (folderPath == null) { return; }

                // Excelファイルパスを作成
                var filePath = Path.Combine(folderPath, "sample.xlsx");

                // 読み書きモードでファイルオープン。ファイル共有は読み取りだけ可の状態
                using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
                using (var package = new ExcelPackage(filePath))
                {
                    // 最初のシートを取得
                    var worksheet = package.Workbook.Worksheets[0]; 
                    worksheet.Cells["A1"].Value = DateTime.Now.ToString("HH:mm:ss");

                    // 変更を一時的にMemoryStreamへ保存
                    using (var temp = new MemoryStream())
                    {
                        package.SaveAs(temp); // 変更内容をMemoryStreamに保存
                        temp.Position = 0;    // 書き込み位置を先頭へ

                        // streamを上書きするため、長さを0にリセット
                        stream.SetLength(0);
                        temp.CopyTo(stream); // MemoryStreamの内容をstreamへコピー
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"エラー: {ex.Message}");
            }
        }
    }
}
投稿日時: 2025-05-18 04:32:18
更新日時: 2025-05-18 05:26:18

内部リンク

Comment

最近の投稿

最近のコメント

タグ

アーカイブ

その他