EPPlusを利用してExcelデータをDataGridViewに読込む C#
★AI による概要
C#のEPPlusは、Microsoft OfficeなしでExcelファイルの読み書き・操作(作成、データ追加、書式設定、グラフ作成など)をプログラムから行える強力なライブラリです。主に.xlsx形式に対応し、NuGetパッケージで追加後、ExcelPackageクラスを使いFileInfoやStream経由でファイルを開き、シートやセルを操作して、データのエクスポートやレポート生成などを効率化できます。ライセンスは5.x系以降、非商用は無料ですが商用利用には有料ライセンスが必要です。
EPPlusの主な機能
- ファイル操作: Excelファイルの新規作成、読み込み、保存。
- シート・セル操作: ワークシートの追加・削除、セルの値設定、書式設定(フォント、色、幅)。
- データ操作: DataTableからのデータ一括ロード、ソート、フィルタリング。
- 高度な機能: 数式、グラフ、画像、テーブルの挿入。
- パフォーマンス: OpenXMLベースで高速。
注意点
- ライセンス: 5.x系以降は商用利用に有料ライセンスが必要(非商用は無料)。
- ファイル形式: 主に
.xlsx形式。旧形式.xlsは読み込めない(Microsoft.Office.Interop.Excelなら可能だが遅い)。 - マクロ: サポートが限定的。
EPPlusは、Excel作業の自動化や動的なレポート作成など、様々なビジネスシーンで強力なツールとなります。
実行画面

1.ファイル選択ボタンで、エクセルファイルを選択します。パスワードが設定されている場合は、選択前にパスワードを入力してください。選択後に、シート名コンボにシート名が追加されます。csvファイルも読込できます(シート名は、Sheet1として扱われます)。
2.シート名コンボよりシート名を選択します。
3.読込ボタンで、内容がDatagGridViewへ表示します。
4.内容を修正できます。行追加、列追加、行消去、列消去、セル範囲コピー&ペーストができます。
5.保存ボタンでDataGridViewの内容をExcel、Csv形式で保存します。
FrmDtaEpplusデザイン



FrmDtaEpplus.CS

//If you are a Noncommercial organization.
ExcelPackage.License.SetNonCommercialOrganization("My Noncommercial organization"); //This will also set the Company property to the organization name provided in the argument.
// If you use EPPlus for Noncommercial personal use.
ExcelPackage.License.SetNonCommercialPersonal("My Name"); //This will also set the Author property to the name provided in the argument.
コード内に、上記宣言が必要となります。
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace KakeiboC_.データ活用
{
public partial class FrmDtaEpplus : Form
{
FileInfo fileInfo;
//control clsResize 画面表示を拡大縮小します。
clsResize _form_resize;
//Form1オブジェクトを保持するためのフィールド
private static FrmKakeibo _form1Instance;
//FrmKakeiboオブジェクトを取得、設定するためのプロパティ
public static FrmKakeibo Form1Instance
{
get
{
return _form1Instance;
}
set
{
_form1Instance = value;
}
}
public FrmDtaEpplus()
{
InitializeComponent();
//clsResize
_form_resize = new clsResize(this); //I put this after the initialize event to be sure that all controls are initialized properly
this.Load += new EventHandler(_Load); //This will be called after the initialization // form_load
this.Resize += new EventHandler(_Resize); //form_resize
//
}
//clsResize _Load
private void _Load(object sender, EventArgs e)
{
_form_resize._get_initial_size();
}
//clsResize _Resize
private void _Resize(object sender, EventArgs e)
{
_form_resize._resize();
}
//ファイル選択
private void button1_Click(object sender, EventArgs e)
{
//OpenFileDialogクラスのインスタンスを作成
OpenFileDialog ofd = new OpenFileDialog();
//はじめのファイル名を指定する
//はじめに「ファイル名」で表示される文字列を指定する
ofd.FileName = "";
//はじめに表示されるフォルダを指定する
//指定しない(空の文字列)の時は、現在のディレクトリが表示される
ofd.InitialDirectory = System.Environment.CurrentDirectory + @"\";
//[ファイルの種類]に表示される選択肢を指定する
//指定しないとすべてのファイルが表示される
ofd.Filter = "Csvファイル(*.csv)|*.xls|Xlsxファイル(*.xlsx)|*.Xlsx|すべてのファイル(*.*)|*.*";
//[ファイルの種類]ではじめに選択されるものを指定する
//2番目の「すべてのファイル」が選択されているようにする
ofd.FilterIndex = 2;
//タイトルを設定する
ofd.Title = "開くファイルを選択してください";
//ダイアログボックスを閉じる前に現在のディレクトリを復元するようにする
ofd.RestoreDirectory = true;
//存在しないファイルの名前が指定されたとき警告を表示する
//デフォルトでTrueなので指定する必要はない
ofd.CheckFileExists = true;
//存在しないパスが指定されたとき警告を表示する
//デフォルトでTrueなので指定する必要はない
ofd.CheckPathExists = true;
//ダイアログを表示する
if (ofd.ShowDialog() == DialogResult.OK)
{
//OKボタンがクリックされたとき、選択されたファイル名を表示する
Console.WriteLine(ofd.FileName);
textBox1.Text = ofd.FileName;
textBox2.Text = "";
comboBox1.Text = "";
comboBox1.Items.Clear();
if (textBox1.Text.EndsWith(".xlsx"))
{
fileInfo = new FileInfo(ofd.FileName);
try
{
//If you are a Noncommercial organization.
ExcelPackage.License.SetNonCommercialOrganization("My Noncommercial organization"); //This will also set the Company property to the organization name provided in the argument.
// If you use EPPlus for Noncommercial personal use.
ExcelPackage.License.SetNonCommercialPersonal("My Name"); //This will also set the Author property to the name provided in the argument.
using (ExcelPackage package = new ExcelPackage(fileInfo,textBox4.Text))
{
Console.WriteLine($"ファイル名: {fileInfo.Name} のシート一覧");
// Workbook.Worksheetsコレクションをループ処理
foreach (var sheet in package.Workbook.Worksheets)
{
// sheet.Nameプロパティでシート名を取得
Console.WriteLine($"- {sheet.Name}");
comboBox1.Items.Add(sheet.Name);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox2.Text= comboBox1.Text;
}
//読込処理
private void importExcel(DataGridViewEx dt, string excelFileName, string sheetName, string password)
{
try
{
//If you are a Noncommercial organization.
ExcelPackage.License.SetNonCommercialOrganization("My Noncommercial organization"); //This will also set the Company property to the organization name provided in the argument.
// If you use EPPlus for Noncommercial personal use.
ExcelPackage.License.SetNonCommercialPersonal("My Name"); //This will also set the Author property to the name provided in the argument.
using (var pack = new ExcelPackage())
{
ExcelWorksheet worksheet = null;
if (excelFileName.EndsWith(".csv"))
{
worksheet = pack.Workbook.Worksheets.Add("Sheet1");
ExcelTextFormat format = new ExcelTextFormat()
{
Delimiter = Convert.ToChar(textBox3.Text)
};
worksheet.Cells[1, 1].LoadFromText(File.ReadAllText(excelFileName), format);
}
else
{
using (var stream = File.OpenRead(excelFileName))
{
pack.Load(stream,password);
}
worksheet = pack.Workbook.Worksheets[sheetName];
}
//ExcelWorksheet worksheet = pack.Workbook.Worksheets[sheetName];
ExcelCellAddress startCell = worksheet.Dimension.Start;
ExcelCellAddress endCell = worksheet.Dimension.End;
dt.Rows.Clear();
dt.Columns.Clear();
dataGridViewEx1.Columns.Clear();
dataGridViewEx1.Rows.Clear();
//列追加
for (int col = 0; col <= endCell.Column; col++)
{
dataGridViewEx1.Columns.Add("columns" + Convert.ToString(col), "c" + Convert.ToString(col));
}
//行追加
for (int row = startCell.Row; row <= endCell.Row; row++)
{
dataGridViewEx1.Rows.Add("");
}
//データ読み取り
for (Int32 row = startCell.Row; row <= endCell.Row; row++)
{
dt.Rows.Add();
for (int col = startCell.Column; col <= endCell.Column; col++)
{
var excelCell = worksheet.Cells[row, col];
var gridViewCell = dt.Rows[row - 1].Cells[col - 1];
if (excelCell.Value != null)
{
gridViewCell.Value = excelCell.Value;
}
else
{
gridViewCell.Value = "";
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//読込
private void button2_Click(object sender, EventArgs e)
{
if (System.IO.File.Exists(textBox1.Text))
{
importExcel(dataGridViewEx1, textBox1.Text, textBox2.Text, textBox4.Text);
//MessageBox.Show("'" + textBox1.Text + "'は存在します。");
}
else
{
MessageBox.Show("ファイル'" + textBox1.Text + "'は存在しません。");
}
}
//終了
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
//保存
private void button4_Click(object sender, EventArgs e)
{
//SaveFileDialogクラスのインスタンスを作成
SaveFileDialog sfd = new SaveFileDialog();
//日付時刻取得
DateTime nowTime;
string str_nowTime;
nowTime = DateTime.Now;
str_nowTime = nowTime.ToString("yyyyMMdd_HHmmss");
//はじめのファイル名を指定する
//はじめに「ファイル名」で表示される文字列を指定する
sfd.FileName = "excelOut_" + str_nowTime;
//はじめに表示されるフォルダを指定する
sfd.InitialDirectory = FrmKakeibo.str_outputdir + "\\";
//[ファイルの種類]に表示される選択肢を指定する
//指定しない(空の文字列)の時は、現在のディレクトリが表示される
sfd.Filter = "Excelファイル(*.xlsx;*.xlsx)|*.xlsx;*.xlsx|すべてのファイル(*.*)|*.*";
//[ファイルの種類]ではじめに選択されるものを指定する
//2番目の「すべてのファイル」が選択されているようにする
sfd.FilterIndex = 1;
//タイトルを設定する
sfd.Title = "保存先のファイルを選択してください";
//ダイアログボックスを閉じる前に現在のディレクトリを復元するようにする
sfd.RestoreDirectory = true;
//既に存在するファイル名を指定したとき警告する
//デフォルトでTrueなので指定する必要はない
sfd.OverwritePrompt = true;
//存在しないパスが指定されたとき警告を表示する
//デフォルトでTrueなので指定する必要はない
sfd.CheckPathExists = true;
//ダイアログを表示する
if (sfd.ShowDialog() == DialogResult.OK)
{
//OKボタンがクリックされたとき、選択されたファイル名を表示する
//Console.WriteLine(sfd.FileName);
string sheet_name = "Sheet1"; //+ str_nowTime;
string fileName2 = Path.GetDirectoryName(sfd.FileName) + "\\csvOut_" + str_nowTime + ".csv";
CreateExcelFile(sfd.FileName,sheet_name, fileName2);
}
}
//データ保存
void CreateExcelFile(string filePath,string sheetName, string filePath2)
{
using (var package = new ExcelPackage())
{
var workbook = package.Workbook;
var worksheet = workbook.Worksheets.Add(sheetName);
//MessageBox.Show(Convert.ToString(dataGridViewEx1.Columns.Count) +"," + Convert.ToString(dataGridViewEx1.Rows.Count));
//列指定
for (int col = 0; col < dataGridViewEx1.Columns.Count; col++)
{
//行指定
for (int row = 0; row < dataGridViewEx1.Rows.Count; row++)
{
worksheet.Cells[row+1,col+1].Value = dataGridViewEx1.Rows[row].Cells[col].Value;
}
}
// シート全体の範囲を指定してCSVとして書き出し
var format = new ExcelOutputTextFormat
{
Encoding = Encoding.UTF8,
Delimiter = ','
};
worksheet.Cells[worksheet.Dimension.Address].SaveToText(
new FileInfo(filePath2),
format
);
// Excelファイルを保存
package.SaveAs(new FileInfo(filePath));
}
}
//(ctrl) + V で貼り付け (ctrl) + C でコピー
private void dataGridViewEx1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.V)
{
//現在のセルのある行から下にペーストする
if (dataGridViewEx1.CurrentCell == null)
return;
int insertRowIndex = dataGridViewEx1.CurrentCell.RowIndex;
int insertColIndex = dataGridViewEx1.CurrentCell.ColumnIndex;
//MessageBox.Show(Convert.ToString(insertRowIndex) + "," + Convert.ToString(insertColIndex));
//クリップボードの内容を取得して、行で分ける
string pasteText = Clipboard.GetText();
if (string.IsNullOrEmpty(pasteText))
return;
pasteText = pasteText.Replace("\r\n", "\n");
pasteText = pasteText.Replace('\r', '\n');
pasteText = pasteText.TrimEnd(new char[] { '\n' });
string[] lines = pasteText.Split('\n');
foreach (string line in lines)
{
//タブで分割
string[] vals = line.Split('\t');
DataGridViewRow row = dataGridViewEx1.Rows[insertRowIndex];
//各セルの値を設定
for (int i = insertColIndex; i < vals.Length + insertColIndex; i++)
{
row.Cells[i].Value = vals[i- insertColIndex];
}
//次の行へ
insertRowIndex++;
}
}
}
//行追加
private void button5_Click(object sender, EventArgs e)
{
dataGridViewEx1.Rows.Add("");
}
//列追加
private void button6_Click(object sender, EventArgs e)
{
int col = dataGridViewEx1.Columns.Count;
dataGridViewEx1.Columns.Add("columns" + Convert.ToString(col), "c" + Convert.ToString(col));
}
//取消
private void button7_Click(object sender, EventArgs e)
{
dataGridViewEx1.Rows.Clear();
dataGridViewEx1.Columns.Clear();
button1.Focus();
}
//行消去
private void button8_Click(object sender, EventArgs e)
{
int row = dataGridViewEx1.CurrentRow.Index;
for (int col = 0; col < dataGridViewEx1.Columns.Count; col++)
{
dataGridViewEx1.Rows[row].Cells[col].Value="";
}
}
//列消去
private void button9_Click(object sender, EventArgs e)
{
int col = dataGridViewEx1.CurrentCell.ColumnIndex;
for (int row = 0; row < dataGridViewEx1.Rows.Count;row++)
{
dataGridViewEx1.Rows[row].Cells[col].Value = "";
}
}
}
}
ExcelOutputTextFormatクラスには次のプロパティがあります。
| 財産 | データ型 | デフォルト値 | 説明 |
|---|---|---|---|
Delimiter | char | ','(コンマ) | 区切り文字 |
TextQualifier | char | '\0'(ヌル) | テキストをカプセル化する文字 |
EOL | string | "\r\n" | 行末文字 |
Culture | CultureInfo | CultureInfo.InvariantCulture | セル値を解析するときに使用するカルチャ |
SkipLinesBeginning | int | 0 | 最後にスキップする行数 |
SkipLinesEnd | int | 0 | 最後にスキップする行数 |
Encoding | Encoding | Encoding.ASCII | FileInfoオブジェクトを使用してディスクからファイルを読み書きする場合にのみ使用されます |
Header | string | null | コンテンツの冒頭に書かれたテキスト |
Footer | string | null | コンテンツの最後に書かれたテキスト |
FirstRowIsHeader | bool | true | 範囲の最初の行にはヘッダーが含まれます。すべてのヘッダーセルは文字列として扱われます。 |
UseCellFormat | bool | true | Text適用されたカルチャでcellsプロパティを使用してください。これは、Formatsコレクション内で書式が設定されていない列にのみ適用されます。SkipLinesBeginning(上記参照)が0より大きい場合、ヘッダーは範囲の最初の行から読み込まれます。TextQualifier(上記参照)が設定されている場合、数値以外の列と日付の列はTextQualifierで囲まれます。 |
Formats | string[] | null | 列に固有の.NETフォーマット。フォーマットは使用されているカルチャに基づいて適用されます。テキスト列の場合は、フォーマットとして$を使用します。 |
DecimalSeparator | string | null | 使用されているカルチャ以外の場合の小数点区切り文字。 |
ThousandsSeparator | string | null | 使用されている文化と異なる場合の千単位区切り |
EncodedTextQualifier | string | null | TextQualifierテキスト内の が設定されている場合に、を何に置き換えるかを指定しますTextQualifier。デフォルトは TextQualifier 文字2つです。たとえば、 " は "" に置き換えられます。 |
Transpose | bool | false | エクスポート時にデータを転置する |
clsResize.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
public class clsResize
{
List<System.Drawing.Rectangle> _arr_control_storage = new List<System.Drawing.Rectangle>();
private bool showRowHeader = false;
public clsResize(Form _form_)
{
form = _form_; //the calling form
_formSize = _form_.ClientSize; //Save initial form size
_fontsize = _form_.Font.Size; //Font size
//ADD
var _controls = _get_all_controls(form);//call the enumerator
FontTable = new Dictionary<string, float>();
ControlTable = new Dictionary<string, System.Drawing.Rectangle>();
foreach (Control control in _controls) //Loop through the controls
{
FontTable.Add(control.Name, control.Font.Size);
ControlTable.Add(control.Name, control.Bounds);
}
//ADD
}
//ADD
Dictionary<string, float> FontTable;
Dictionary<string, System.Drawing.Rectangle> ControlTable;
//ADD
private float _fontsize { get; set; }
private System.Drawing.SizeF _formSize { get; set; }
private Form form { get; set; }
public void _get_initial_size() //get initial size//
{
var _controls = _get_all_controls(form);//call the enumerator
foreach (Control control in _controls) //Loop through the controls
{
_arr_control_storage.Add(control.Bounds); //saves control bounds/dimension
//If you have datagridview
if (control.GetType() == typeof(DataGridViewEx)) //20251228
_dgv_Column_Adjust(((DataGridViewEx)control), showRowHeader); //20251228
}
}
public void _resize() //Set the resize
{
double _form_ratio_width = (double)form.ClientSize.Width / (double)_formSize.Width; //ratio could be greater or less than 1
double _form_ratio_height = (double)form.ClientSize.Height / (double)_formSize.Height; // this one too
var _controls = _get_all_controls(form); //reenumerate the control collection
int _pos = -1;//do not change this value unless you know what you are doing
foreach (Control control in _controls)
{
//ADD
this._fontsize = FontTable[control.Name]; //<-取得したコントロールのフォントサイズ値で上書きするためにこれを追加
//ADD
// do some math calc
_pos += 1;//increment by 1;
System.Drawing.Size _controlSize = new System.Drawing.Size((int)(_arr_control_storage[_pos].Width * _form_ratio_width),
(int)(_arr_control_storage[_pos].Height * _form_ratio_height)); //use for sizing
System.Drawing.Point _controlposition = new System.Drawing.Point((int)
(_arr_control_storage[_pos].X * _form_ratio_width), (int)(_arr_control_storage[_pos].Y * _form_ratio_height));//use for location
//set bounds
control.Bounds = new System.Drawing.Rectangle(_controlposition, _controlSize); //Put together
//Assuming you have a datagridview inside a form()
//if you want to show the row header, replace the false statement of
//showRowHeader on top/public declaration to true;
if (control.GetType() == typeof(DataGridViewEx)) //20251228
_dgv_Column_Adjust(((DataGridViewEx)control), showRowHeader); //20251228
//Font AutoSize
control.Font = new System.Drawing.Font(form.Font.FontFamily,
(float)(((Convert.ToDouble(_fontsize) * _form_ratio_width) / 2) +
((Convert.ToDouble(_fontsize) * _form_ratio_height) / 2)));
}
}
private void _dgv_Column_Adjust(DataGridViewEx dgv, bool _showRowHeader) //if you have Datagridview 20251228
//and want to resize the column base on its dimension.
{
int intRowHeader = 0;
const int Hscrollbarwidth = 5;
if (_showRowHeader)
intRowHeader = dgv.RowHeadersWidth;
else
dgv.RowHeadersVisible = false;
for (int i = 0; i < dgv.ColumnCount; i++)
{
if (dgv.Dock == DockStyle.Fill) //in case the datagridview is docked
dgv.Columns[i].Width = ((dgv.Width - intRowHeader) / dgv.ColumnCount);
else
dgv.Columns[i].Width = ((dgv.Width - intRowHeader - Hscrollbarwidth) / dgv.ColumnCount);
}
}
private static IEnumerable<Control> _get_all_controls(Control c)
{
return c.Controls.Cast<Control>().SelectMany(item =>
_get_all_controls(item)).Concat(c.Controls.Cast<Control>()).Where(control =>
control.Name != string.Empty);
}
}
DataGridvViewEx.cs DataGridViewの拡張
//コードを隠すコードを選択
using System;
using System.Windows.Forms;
/// <summary>
/// Enterキーが押された時に、Tabキーが押されたのと同じ動作をする
/// (現在のセルを隣のセルに移動する)DataGridView
/// </summary>
public class DataGridViewEx : DataGridView
{
private DataGridView dataGridView1;
protected override bool ProcessDialogKey(Keys keyData)
{
// セルの編集モード時にEnterが押されると次行に移ってしまうので、右隣のセルに移動させる
if ((keyData & Keys.KeyCode) == Keys.Enter)
{
// Tabキーの処理を行う
return this.ProcessTabKey(keyData);
}
// 既定の処理を行う
return base.ProcessDialogKey(keyData);
}
/// DataGridView での移動に使用されるキーを処理します。
protected override bool ProcessDataGridViewKey(KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && e.Handled == false)
{
// イベントを処理済にする
e.Handled = true;
if (this.CurrentCell != null)
{
// 右下セルのときは次のコントロールにフォーカス移動
if (this.CurrentCell.RowIndex == this.Rows.GetLastRow(DataGridViewElementStates.Visible) &&
this.CurrentCell.ColumnIndex == this.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None).Index &&
e.Modifiers != Keys.Shift)
{
return this.FindForm().SelectNextControl(this.FindForm().ActiveControl, true, true, true, true);
}
// 左上のセルでShift + Enterが押されたときは前のコントロールにフォーカス移動
if (this.CurrentCell.RowIndex == 0 &&
this.CurrentCell.ColumnIndex == 0 &&
e.Modifiers == Keys.Shift)
{
return this.FindForm().SelectNextControl(this.FindForm().ActiveControl, false, true, true, true);
}
}
// Enterキーが押されらTabキーの処理を行う
return this.ProcessTabKey(e.KeyData);
}
// 既定の処理を行う
return base.ProcessDataGridViewKey(e);
}
private void InitializeComponent()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(0, 0);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(240, 150);
this.dataGridView1.TabIndex = 0;
//
// DataGridViewEx
//
this.RowTemplate.Height = 21;
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
this.ResumeLayout(false);
}
}