MSDN.WhiteKnight - Stack Overflow answers
Ответ на "Не открывается .xlsx в datagrid"
Answer 872834
Вы указываете в запросе имя файла, а нужно - имя листа
Вы игнорируете все исключения, поэтому вы не можете даже увидеть сообщение об ошибке
Вывести содержимое первого листа можно так:
OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "XML Files (*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb) |*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb"; openFileDialog1.FilterIndex = 3; openFileDialog1.Multiselect = false; openFileDialog1.InitialDirectory = @"Desktop"; Nullable<bool> result = openFileDialog1.ShowDialog(); if (result == true) { string pathName = openFileDialog1.FileName; string fileName = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName); DataTable tbContainer = new DataTable(); string strConn = string.Empty; string sheetName; FileInfo file = new FileInfo(pathName); if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); } string extension = file.Extension; switch (extension) { case ".xls": strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; break; case ".xlsx": strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; break; default: strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; break; } OleDbConnection cnnxls = new OleDbConnection(strConn); using (cnnxls) { cnnxls.Open(); DataTable dtSchema = cnnxls.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); sheetName = dtSchema.Rows[0].Field<string>("TABLE_NAME"); OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}]", sheetName), cnnxls); oda.Fill(tbContainer); } grid1.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = tbContainer }); }
Content is retrieved from StackExchange API.
Auto-generated by ruso-archive tools.