“外部表格不符合预期格式。”在读取以2010格式保存的excel(.xlsx)文件时?

时间:2017-06-14 04:37:21

标签: excel oledb

当我正在阅读excel(2010)文件时,“外部表格不是预期的格式。”发生错误。我正在使用Oledb连接来读取excel文件。请为此问题提供最佳解决方案。谢谢......

        string connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;IMEX=1;HDR=YES'";
        using (OleDbConnection conn = new OleDbConnection(connectionstring))
        {
            try
            {
                conn.Open();
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = conn;
                System.Data.DataTable dtExcelSchema;
                dtExcelSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                string firstSheet = "";
                int count = dtExcelSchema.Rows.Count;
                conn.Close();
                //Read Data from First Sheet
                conn.Open();
                DataTable dt = new DataTable();
                var tempDataTable = (from dataRow in dtExcelSchema.AsEnumerable()
                                     where !dataRow["TABLE_NAME"].ToString().Contains("FilterDatabase")
                                     select dataRow).CopyToDataTable();
                dt = tempDataTable;
                firstSheet = dt.Rows[0]["TABLE_NAME"].ToString();
                if (!firstSheet.EndsWith("$"))
                {
                    firstSheet = dt.Rows[0]["TABLE_NAME"].ToString() + "$";
                }
                cmd.CommandText = "select * from [" + firstSheet + "]";
                string query1 = "SELECT count(*) FROM [" + firstSheet + "]";
                cmd = new OleDbCommand(query1, conn);
                cmd.CommandText = query1;
                if (Convert.ToInt32(cmd.ExecuteScalar()) > 0)
                {
                    string sheetName = firstSheet.Replace(" ", "").Replace("'", "");
                    string query = "SELECT * FROM [" + sheetName + "]";
                    dtnew.TableName = firstSheet;
                    OleDbDataAdapter oda = new OleDbDataAdapter(query, conn);
                    oda.Fill(dtnew);
                }
            }
            catch (Exception ex)
            {

            }
        }

0 个答案:

没有答案