Excel外部表格不是预期的格式

时间:2014-02-07 09:53:47

标签: excel oledbconnection

我从同一个Excel文件中运行此代码两次,它工作正常,我得到了正确的表。但是,当我第三次尝试运行它时崩溃并抛出外部表不是预期的格式。

Filename = filename;
        if (ExcelSet == null)
        {
            string HDR = firstRowContainsColumnNames ? "Yes" : "No";
            string strConn;
            if (filename.Substring(filename.LastIndexOf('.')).ToLower() == ".xlsx")
            {
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Filename + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=1\"";
            }
            else if (filename.Substring(filename.LastIndexOf('.')).ToLower() == ".xls")
            {
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Filename + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=1\"";
            }
            else
            {
                throw new Exception("File is not an Excel file");
            }

            DataSet ds = new DataSet();

            using (OleDbConnection conn = new OleDbConnection(strConn))
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }


                DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

                foreach (DataRow schemaRow in schemaTable.Rows)
                {
                    string sheet = schemaRow["TABLE_NAME"].ToString();

                    if (!sheet.EndsWith("_"))
                    {
                        try
                        {
                            OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
                            cmd.CommandType = CommandType.Text;

                            DataTable outputTable = new DataTable(sheet);
                            ds.Tables.Add(outputTable);
                            new OleDbDataAdapter(cmd).Fill(outputTable);
                            outputTable.Dispose();
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.Message + string.Format("Sheet: {0}.File.F{1}", sheet, Filename), ex);
                        }
                    }
                }

                conn.Close();
                conn.Dispose();

            }


            ExcelSet = ds;
        }

我不知道为什么它会出现问题,有人遇到同样的问题?

0 个答案:

没有答案