微软NET提供了一个交互的方法,通过使用ADO.NET与Microsoft Office程序。可以使用内置的OLEDB来访问Excel的XLS表格。下面的例子演示了如何在C#编程读取Excel工作表。需要引用System.Data.OleDb库
using System;
using System.Data.OleDb;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string connString = "Provider=Microsoft.Jet.OleDb.4.0; data source=c:\\sample.xls; Extended Properties=Excel 8.0;";
// Select using a Worksheet name
string selectqry = "SELECT * FROM [Sheet1$]";
OleDbConnection conn = new OleDbConnection(connString);
OleDbCommand cmd = new OleDbCommand(selectqry,con);
try
{
con.Open();
OleDbDataReader theDatardr = cmd.ExecuteReader();
while (theDatardr.Read())
{
Console.WriteLine("{0}: {1} ({2}) – {3} ({4})", theDatardr.GetString(0),theDatardr.GetString(1),theDatardr.GetString(2),theDatardr.GetString(3),theDatardr.GetString(4));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Dispose();
}
}
}
}
