これは、初心者が試してみることもできるものです。
Ranges を使用する例が必要な場合は、お知らせください。その例を投稿することもできますが、始めるにはこれで十分です。コード Sorce= を Excel ファイルのファイル パスと一致するように変更します。
using System.Data;
using System.Data.OleDb;
...
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Book1.xls;Extended Properties=Excel 8.0");
OleDbDataAdapter da = new OleDbDataAdapter("select * from MyObject", con);
DataTable dt = new DataTable();
da.Fill(dt);
Excelファイルの読み方の完全な例が必要な場合は、別の例をご覧ください
以下は、Excel ファイルを読み取るために必要なコード全体です。
void Read_My_Excel_File()
{
// Test.xls is in the C:\
string connectionString = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + C:\Test.xls + ";";
connectionString += "Extended Properties=Excel 8.0;";
// always read from the sheet1.
OleDbCommand myCommand = new OleDbCommand("Select * from [Sheet1$];");
OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
myCommand.Connection = myConnection;
OleDbDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
// it can read upto 5 columns means A to E. In your case if the requirement is different then change the loop limits a/c to it.
for (int i = 0; i < 5; i++)
{
Response.Write(myReaderIdea.ToString() + " ");
}
Response.Write("<br>");
}
myConnection.Close();
}