Excel文件解析

1.创建Excel文件

   创建名称是"TextFile1.xls"的文档,设置属性“复制到输出目录 - 如果较新则复制”。在工程运行时,会自动将该txt文件复制到bin下面。

2.解析Excel文件

class Program
{
    static void Main(string[] args)
    {
        string fileName = "TextFile1.xls";
        //连接字符串
        string strConnection = "Provider=Microsoft.Jet.OleDb.4.0;" +  
        "Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
        //创建连接对象
        OleDbConnection connection = new OleDbConnection(strConnection);
        //打开连接
        connection.Open();
        //查询数据
        string query = "select * from [Sheet1$]";
        OleDbDataAdapter adapter = new OleDbDataAdapter(query, connection);
        //将查询结果填充到DataSet中
        DataSet dataSet = new DataSet();           
        adapter.Fill(dataSet);
        //关闭连接对象
        connection.Close();

        //获取集合中的所有表格
        DataTableCollection dataCollection = dataSet.Tables;
        foreach (DataTable item in dataCollection)
        {
            //取得Table中所有的行
            DataRowCollection rowCollection = item.Rows;
            foreach (DataRow row in rowCollection)
            {
                //取第一列的数据输出
                Console.WriteLine(row[0]);
            }
        }
        Console.ReadKey();
    }
}

猜你喜欢

转载自blog.csdn.net/liyazhen2011/article/details/81350003
今日推荐