zoukankan      html  css  js  c++  java
  • C# 读取Excel

    直接添代码:

     public void connExcel(string strPath)
            {
                //string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';";
                string strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1';";
                
                OleDbDataReader myDataReader = null;
                OleDbConnection myOleDbConnection = new OleDbConnection(strConn);
                OleDbCommand myOleDbCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", myOleDbConnection);
    
                try
                {
                    myOleDbConnection.Open();
                    myDataReader = myOleDbCommand.ExecuteReader();
                    while (myDataReader.Read())
                    {
                        Console.WriteLine("序号:" + myDataReader.GetValue(0));//列1
                        Console.WriteLine("标题:" + myDataReader.GetValue(1));//列2
                        Console.WriteLine("预期结果:" + myDataReader.GetValue(2));//列3
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                finally
                {
                    // Always call Close when done reading.
                    if (myDataReader != null)
                        myDataReader.Close();
    
                    // Close the connection when done with it.
                    if (myOleDbConnection != null)
                        myOleDbConnection.Close();
                }
            }
    View Code

    遇到问题:

    1.open时,报“找不到可安裝的ISAM解決方法”

    解决方法:'Excel 8.0;HDR=Yes;IMEX=1;'这个要用单引号引起来

    2.报错:外部表不是预期的格式错误

    错误原因1: 由于Excel 97-2003的连接格式与Excel 2010 的 不同造成。

    解决方法:

    //2003(Microsoft.Jet.Oledb.4.0)
    string strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", excelFilePath);

    //2007 , 2010(Microsoft.ACE.OLEDB.12.0)
    string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'", excelFilePath);

    3.Access有密碼設置時,當用C#連接Access Database時可能會出現"找不到可安裝的ISAM"。

    解决方法:string dsn = "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:DataBase Password=123;Data Source=C:\...\*.mdb";

  • 相关阅读:
    NodeJs学习历程
    MongoDb学习历程
    递归函数为什么要防止栈溢出
    *args 是可变参数,args 接收的是一个 tuple; **kw 是关键字参数,kw 接收的是一个 dict。
    list和tuple的区别
    python源码阅读
    常用的线程池有哪些?
    备份
    假设你正在爬楼梯,需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶,你有多少种不同的方法可以爬到楼顶呢?
    最后一个单词的长度
  • 原文地址:https://www.cnblogs.com/yangxia-test/p/3962489.html
Copyright © 2011-2022 走看看