突然无法使用带有c#的microsoft.jet.4.0打开excel文件。连接字符串我什么都没改变?

时间:2012-07-04 09:42:39

标签: c# excel oledbconnection

所以我正在研究这项工作,将excel指令列表转换为更好看,格式化的word文档。我一直在连接到excel文档,然后将文件存储到数据表中以便于访问。

当我开始收到错误时,我终于得到了边框和正确的文字文件:     External table is not in the expected format.

这是完整的连接算法:

 public static DataTable getWorkSheet(string excelFile =
            "C:\\Users\\Mitch\\Dropbox\\Work tools\\Excel for andrew\\Air Compressor PM's.xlsx") {
            string connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFile
                                + ";Extended Properties='Excel 8.0;HDR=YES;'";
            string sql = null;
            string worksheetName = null;
            string[] Headers = new string[4];
            DataTable schema = null;
            DataTable worksheet = null;
            DataSet workbook = new DataSet();
            //Preparing and opening connection
            OleDbConnection objconn = new OleDbConnection(connection);
            objconn.Open();
            //getting the schema data table
            schema = objconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            worksheetName = schema.Rows[0]["Table_Name"].ToString();
            //Each worksheet will have a varying name, so the name is just called from
            //the dataTable.rows array. Can be later modified to use multiple
            //worksheets within a workbook.
            sql = "SELECT * FROM[" + worksheetName + "]";

            //data adapter
            OleDbDataAdapter objAdapter = new OleDbDataAdapter();
            //pass the sql
            objAdapter.SelectCommand = new OleDbCommand(sql, objconn);
            //populate the dataset
            objAdapter.Fill(workbook);
            //Remove spaces from the headers.
            worksheet = workbook.Tables[0];
            for (int x = 0; x < Headers.Count(); x++) {
                Headers[x] = worksheet.Columns[x].ColumnName;
                worksheet.Columns[x].ColumnName = worksheet.Columns[x].ColumnName.Replace(" ", "");
            }
            return worksheet;            
        }//end of getWorksheet
编辑:我从Dropbox以前的版本中提取了我的旧代码,这些版本肯定正在工作以及重新下载我知道正在工作的excel文档的副本.....给出了什么?我的电脑有什么变化吗?

1 个答案:

答案 0 :(得分:1)

您正在连接到2007/2010 Excel文件(* .xlsx,* .xlsm)。您需要更新的2010驱动程序(Ace),which can be downloaded for free。可以从http://connectionstrings.com/Excelhttp://connectionstrings.com/Excel-2007

获取正确的连接字符串
相关问题