C# でExcelファイルにアクセスするサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Data; | |
using System.Drawing; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Windows.Forms; | |
using Excel = Microsoft.Office.Interop.Excel; | |
namespace cs_excel | |
{ | |
public partial class Form1 : Form | |
{ | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
// 指定されたワークシート名のインデックスを返すメソッド | |
private int getSheetIndex(string sheetName, Excel.Sheets shs) | |
{ | |
int i = 0; | |
foreach (Excel.Worksheet sh in shs) | |
{ | |
if (sheetName == sh.Name) | |
{ | |
return i + 1; | |
} | |
i += 1; | |
} | |
return 0; | |
} | |
private void Form1_Load(object sender, EventArgs e) | |
{ | |
string excelName = "C:\\temp.xls"; | |
Excel.Application oXls; // Excelオブジェクト | |
Excel.Workbook oWBook; // workbookオブジェクト | |
oXls = new Excel.Application(); | |
oXls.Visible = true; // 確認のためExcelのウィンドウを表示する | |
// Excelファイルをオープンする | |
oWBook = (Excel.Workbook)(oXls.Workbooks.Open( | |
excelName, // オープンするExcelファイル名 | |
Type.Missing, // (省略可能)UpdateLinks (0 / 1 / 2 / 3) | |
Type.Missing, // (省略可能)ReadOnly (True / False ) | |
Type.Missing, // (省略可能)Format | |
// 1:タブ / 2:カンマ (,) / 3:スペース / 4:セミコロン (;) | |
// 5:なし / 6:引数 Delimiterで指定された文字 | |
Type.Missing, // (省略可能)Password | |
Type.Missing, // (省略可能)WriteResPassword | |
Type.Missing, // (省略可能)IgnoreReadOnlyRecommended | |
Type.Missing, // (省略可能)Origin | |
Type.Missing, // (省略可能)Delimiter | |
Type.Missing, // (省略可能)Editable | |
Type.Missing, // (省略可能)Notify | |
Type.Missing, // (省略可能)Converter | |
Type.Missing, // (省略可能)AddToMru | |
Type.Missing, // (省略可能)Local | |
Type.Missing // (省略可能)CorruptLoad | |
)); | |
// 与えられたワークシート名から、Worksheetオブジェクトを得る | |
string sheetName = "sheet1"; | |
Excel.Worksheet oSheet; // Worksheetオブジェクト | |
oSheet = (Excel.Worksheet)oWBook.Sheets[ | |
getSheetIndex(sheetName, oWBook.Sheets)]; | |
string sCellVal; | |
Excel.Range rng; // Rangeオブジェクト | |
rng = (Excel.Range)oSheet.Cells[1, 1]; | |
sCellVal = rng.Text.ToString(); // A1セルの内容 | |
MessageBox.Show(sCellVal); | |
oXls.Quit(); | |
//COM解放 | |
System.Runtime.InteropServices.Marshal.ReleaseComObject(oXls); | |
} | |
} | |
} |
なお予めExcelのCOMコンポーネントへの参照をプロジェクトに追加する必要があります。これには[参照の追加]ウィンドウで[COM]タブを選択し、「Microsoft Excel 15.0 Object Library」(Excel 2013の場合。Excel 2007の場合は「Microsoft Excel 12.0 Object Library」を選択します)。
以下を参考にさせていただきました。 http://www.atmarkit.co.jp/fdotnet/dotnettips/717excelfile/excelfile.html
0 件のコメント:
コメントを投稿