简体   繁体   中英

Transferring data from Excel to dataGridView

I have a problem when I want to transfer data from Excel to dataGridView in C#.

My Excel's column has numeric and alphanumeric values. But for example, if the column has 3 numbers and 2 alphanumeric values then only the numbers are shown in the dataGridView, and vice versa. Why aren't all the values shown? The next is what happen:

Excel's Column:                   DataGridView's Column:
   45654                               45654
   P745K 
   31233                               31233
   23111                               23111
   45X2Y

Here is my code to load the dataGridView:

string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\test.xls;Extended Properties=""Excel 8.0;HDR=YES;""";

DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");

DbDataAdapter adapter = factory.CreateDataAdapter();

DbCommand selectCommand = factory.CreateCommand();
selectCommand.CommandText = "SELECT * FROM [sheet1$]";

DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;

selectCommand.Connection = connection;

adapter.SelectCommand = selectCommand;

data = new DataSet();

adapter.Fill(data);

dataGridView1.DataSource = data.Tables[0].DefaultView;

Try formatting all the cells as text in the excel sheet before importing. (Which you could do manually or programatically)

You could just add "IMEX=1" into your connection string like ↓

string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\test.xls;Extended Properties=""Excel 8.0;HDR=YES;IMEX=1""";

It would forceably read all values in as strings .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM