将Excel导入到Datagrid

我试图把一个excel文件放到我的程序中,这样我可以处理数据并导出它。 我正在使用OleDB访问访问文件,并试图将其传递给一个数据表,以便我可以查看它并使用它在一个winform中。 这是我正在使用的代码:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SqlClient; using System.Data.OleDb; using System.Windows; using System.Windows.Forms; using System.Globalization; using System.Runtime.Versioning; using System.Threading; namespace DataImportServices { public class ExcelImport : IDataImport { public DataTable ImportData(OpenFileDialog openFile) { var dataTable = new DataTable(); string query; var hasHeaders = false; var HDR = hasHeaders ? "Yes" : "No"; string connectionString; if (openFile.FileName.Substring(openFile.FileName.LastIndexOf(".")).ToLower() == ".xlsx") { connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFile.FileName + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\""; } else { connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + openFile.FileName + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\""; } using (OleDbConnection cn = new OleDbConnection(connectionString)) { cn.Open(); DataTable schemaTable = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); DataRow schemaRow = schemaTable.Rows[0]; string sheet = schemaRow["TABLE_NAME"].ToString(); if (!sheet.EndsWith("_")) { query = "SELECT * FROM [" + openFile.FileName + "]"; using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, cn)) { dataTable.Locale = CultureInfo.CurrentCulture; dataAdapter.Fill(dataTable); //The error occurs here with a "" is not an acceptable. If I put a name ie "Data" it says its not an adorecord. } } } return (dataTable); } } } 

我正在尝试用OleDBAdapter(dataAdapter)填充dataTable的错误。 它抛出一个exception,要求一个ADODBrecordset,尽pipe只有一个DataTable覆盖。 我该如何解决这个问题? 还是我错过了什么?

先谢谢你。

你可以使用像EpPlus这样的库。 这种支持擅长本地而不使用ole或excel。

您可以将数据作为数组加载并直接访问它。

http://epplus.codeplex.com/wikipage?title=LinqExample

您可以尝试使用Exportable读取excel内容。 是我之前开发的一个小型库,现在作为OpenSource在Nuget上发布。

基本上,你可以像这样读取一个Excel文件:

 IImportEngine engine = new ExcelImportEngine(); var key = engine.AddContainer<DummyPersonWithAttributes>(); engine.SetDocument(pathToFile); //or MemoryStream instance var data = engine.GetList<DummyPersonWithAttributes>(key); 

你可以在这里获得更多的信息