外部表格不是xls文件的预期格式

时间:2018-01-11 08:30:47

标签: excel connection-string oledb ole ms-jet-ace

从excel获取数据时我遇到连接问题。它在.xlsx文件中工作得很好,但是对于Excel 8.0的格式,它不能用于.xls文件。我怎么解决这个问题?我试图添加“HDR:YES”或“IMEX:1”但不起作用。这是我的代码;

                string connString = "";
                        if (sFileExtension == ".xls")

                            connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(string.Format("Upload/Belgeler/Tmp/{0}_{1}/{2}", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString(), sFileName)) + ";Extended Properties=Excel 8.0";
                        else if (sFileExtension == ".xlsx")
                            connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(string.Format("Upload/Belgeler/Tmp/{0}_{1}/{2}", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString(), sFileName)) + ";Extended Properties=Excel 12.0";



                        // Create the connection object
                        OleDbConnection oledbConn = new OleDbConnection(connString);
                        try
                        {
                            // Open connection
                            oledbConn.Open();

                            DataTable dtSheetName = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                            if (dtSheetName == null || dtSheetName.Rows.Count == 0)
                            {
                                if (oledbConn.State == ConnectionState.Open)
                                    oledbConn.Close();
                                throw new Exception("Excel belgesi içinde Sayfa[Sheet] bulunamadı!");
                            }
                            // Create OleDbCommand object and select data from worksheet Sheet1 
                            DataSet ds = new DataSet();
                            using (OleDbCommand cmdSheet = new OleDbCommand("SELECT * FROM [" + dtSheetName.Rows[0]["TABLE_NAME"].ToString() + "]", oledbConn))
                            {
                                OleDbDataAdapter oleda = new OleDbDataAdapter();
                                oleda.SelectCommand = cmdSheet;
                                oleda.Fill(ds, "ExcelFields");

                            }
                            oledbConn.Close();

0 个答案:

没有答案