Created
December 14, 2012 16:43
-
-
Save cofearabi/4286797 to your computer and use it in GitHub Desktop.
(c#) access to the excel sheet and display the value of A1 cell.
This file contains 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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment