Excel操作

1,使用OLEDB操作Excel

关于OLEDB介绍参考 http://www.cnblogs.com/moss_tan_jun/archive/2012/07/28/2612889.html

2,连接字符串

"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
public static void Main (string[] args)
{
    string fileName = "装备信息.xls";
    string connectStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
    //string connectStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
    OleDbConnection connection = new OleDbConnection (connectStr);
    connection.Open ();

    string sql = "select * from [Sheet1$]";
    DataSet dataSet = new DataSet ();//可以存放DataTable

    OleDbDataAdapter adapter = new OleDbDataAdapter (sql, connection);
    adapter.Fill (dataSet);//将查询的结果存放到一个dataSet中

    connection.Close ();

    //取出数据
    DataTableCollection tableCollection = dataSet.Tables;//取出所有表

    DataTable table = tableCollection [0];

    DataRowCollection rowCollection = table.Rows;//取得所有行

    foreach (DataRow row in rowCollection) {
        for (var i = 0; i < 8; i++) {
            Console.Write (row [i] + " ");
        }
        Console.WriteLine ();
    }
}

results matching ""

    No results matching ""