datagridview-import-excel ソースコード全文
DataGridView_Import_Excel.slnx
<Solution> <Project Path="DataGridView_Import_Excel/DataGridView_Import_Excel.csproj" /></Solution>DataGridView_Import_Excel/DataGridView_Import_Excel.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <OutputType>WinExe</OutputType> <TargetFramework>net10.0-windows</TargetFramework> <Nullable>enable</Nullable> <UseWindowsForms>true</UseWindowsForms> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup>
<ItemGroup> <COMReference Include="Microsoft.Office.Interop.Excel"> <WrapperTool>tlbimp</WrapperTool> <VersionMinor>9</VersionMinor> <VersionMajor>1</VersionMajor> <Guid>00020813-0000-0000-c000-000000000046</Guid> <Lcid>0</Lcid> <Isolated>false</Isolated> <EmbedInteropTypes>true</EmbedInteropTypes> </COMReference> </ItemGroup>
<ItemGroup> <None Update="商品リスト.xlsx"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup>
</Project>DataGridView_Import_Excel/DataGridView_Import_Excel.csproj.user
<?xml version="1.0" encoding="utf-8"?><Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Compile Update="Form1.cs"> <SubType>Form</SubType> </Compile> </ItemGroup></Project>DataGridView_Import_Excel/Form1.cs
using System.Data;using System.Runtime.InteropServices;// 長い名前空間を省略するため、ファイルの最上部で別名を定義しますusing Excel = Microsoft.Office.Interop.Excel;
namespace DataGridView_Import_Excel;
public partial class Form1 : Form{ private DataTable _dataTable = new DataTable();
public Form1() { InitializeComponent(); InitializeDataGridView();
// ボタンのクリックイベントを購読 btnImportExcel.Click += btnImportExcel_Click; }
private void InitializeDataGridView() { // エクスポート時と同じデータ構造(3列)で DataTable を定義 _dataTable.Columns.Add("Code", typeof(string)); _dataTable.Columns.Add("Name", typeof(string)); _dataTable.Columns.Add("Price", typeof(int));
dataGridView1.DataSource = _dataTable; dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; }
/// <summary> /// 「Excel読込」ボタンのクリックイベント /// </summary> private void btnImportExcel_Click(object? sender, EventArgs e) { // 読込元のファイルをユーザーに選択させる(OpenFileDialog) using var ofd = new OpenFileDialog(); ofd.Filter = "Excel ブック (*.xlsx)|*.xlsx|従来の Excel ブック (*.xls)|*.xls"; if (ofd.ShowDialog() != DialogResult.OK) return;
// 既存のグリッドデータを一度クリア _dataTable.Rows.Clear();
// Excel関係のオブジェクトは try-finally で確実に解放するために外側で宣言します Excel.Application? excelApp = null; Excel.Workbooks? workbooks = null; Excel.Workbook? workbook = null; Excel.Sheets? sheets = null; Excel.Worksheet? worksheet = null; Excel.Range? usedRange = null;
try { excelApp = new Excel.Application(); workbooks = excelApp.Workbooks; workbook = workbooks.Open(ofd.FileName); sheets = workbook.Sheets; worksheet = (Excel.Worksheet)sheets[1]; // 1番目のシートを取得 usedRange = worksheet.UsedRange;
// セルを1つずつループで読むと遅いため、2次元配列として一括で読み込みます object[,] dataArray = (object[,])usedRange.Value2;
int rowCount = dataArray.GetLength(0); int colCount = dataArray.GetLength(1);
// 1行目はヘッダー(列名)のため、データ行である2行目からループを開始 for (int r = 2; r <= rowCount; r++) { // 配列が Null の場合や列数が足りない場合を考慮した安全な値の取得 string code = dataArray[r, 1]?.ToString() ?? ""; string name = dataArray[r, 2]?.ToString() ?? "";
// 数値型(Price)への安全なパース int price = 0; if (dataArray[r, 3] != null) { int.TryParse(dataArray[r, 3].ToString(), out price); }
// データの追加(空行をスキップしたい場合は、ここで適宜条件を挟みます) if (!string.IsNullOrEmpty(code) || !string.IsNullOrEmpty(name)) { _dataTable.Rows.Add(code, name, price); } }
MessageBox.Show("Excel データを正常に読み込みました。", "インポート完了", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show($"エラーが発生しました:\n{ex.Message}", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { // 参照リーク(バックグラウンドに Excel が残る現象)を防止する解放処理 if (workbook != null) { workbook.Close(false); // 上書き保存せずに閉じる } if (excelApp != null) { excelApp.Quit(); }
// COM オブジェクトを割り当てた逆順で確実に解放 if (usedRange != null) Marshal.ReleaseComObject(usedRange); if (worksheet != null) Marshal.ReleaseComObject(worksheet); if (sheets != null) Marshal.ReleaseComObject(sheets); if (workbook != null) Marshal.ReleaseComObject(workbook); if (workbooks != null) Marshal.ReleaseComObject(workbooks); if (excelApp != null) Marshal.ReleaseComObject(excelApp); } }}DataGridView_Import_Excel/Form1.Designer.cs
namespace DataGridView_Import_Excel{ partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null;
/// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); }
#region Windows Form Designer generated code
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { tableLayoutPanel1 = new TableLayoutPanel(); btnImportExcel = new Button(); dataGridView1 = new DataGridView(); tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit(); SuspendLayout(); // // tableLayoutPanel1 // tableLayoutPanel1.ColumnCount = 1; tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F)); tableLayoutPanel1.Controls.Add(btnImportExcel, 0, 1); tableLayoutPanel1.Controls.Add(dataGridView1, 0, 0); tableLayoutPanel1.Dock = DockStyle.Fill; tableLayoutPanel1.Location = new Point(0, 0); tableLayoutPanel1.Name = "tableLayoutPanel1"; tableLayoutPanel1.RowCount = 2; tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 90.44444F)); tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 9.555555F)); tableLayoutPanel1.Size = new Size(800, 450); tableLayoutPanel1.TabIndex = 0; // // btnImportExcel // btnImportExcel.Dock = DockStyle.Fill; btnImportExcel.Location = new Point(3, 410); btnImportExcel.Name = "btnImportExcel"; btnImportExcel.Size = new Size(794, 37); btnImportExcel.TabIndex = 0; btnImportExcel.Text = "エクセルデータをインポート"; btnImportExcel.UseVisualStyleBackColor = true; // // dataGridView1 // dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridView1.Dock = DockStyle.Fill; dataGridView1.Location = new Point(3, 3); dataGridView1.Name = "dataGridView1"; dataGridView1.RowHeadersWidth = 62; dataGridView1.Size = new Size(794, 401); dataGridView1.TabIndex = 1; // // Form1 // AutoScaleDimensions = new SizeF(10F, 25F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(800, 450); Controls.Add(tableLayoutPanel1); Name = "Form1"; Text = "Form1"; tableLayoutPanel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit(); ResumeLayout(false); }
#endregion
private TableLayoutPanel tableLayoutPanel1; private Button btnImportExcel; private DataGridView dataGridView1; }}DataGridView_Import_Excel/Form1.resx
<?xml version="1.0" encoding="utf-8"?><root> <!-- Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types.
Example:
... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data>
There are any number of "resheader" rows that contain simple name/value pairs.
Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set.
The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader></root>DataGridView_Import_Excel/Program.cs
namespace DataGridView_Import_Excel{ internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); Application.Run(new Form1()); } }}DataGridView_Import_Excel/���i���X�g.xlsx
🗎 バイナリファイル(画像・実行ファイル等)のため、内容の表示は省略しています。 全体は ZIP ダウンロード でご確認ください。