2011-11-21 85 views
2

當我想將數據從Excel傳輸到C#中的dataGridView時,出現問題。將數據從Excel傳輸到dataGridView

我的Excel的列有數字和字母數字值。但是例如,如果列有3個數字和2個字母數字值,那麼只有數字顯示在dataGridView中,反之亦然。爲什麼沒有顯示所有的值?下一個是什麼情況:

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

這裏是我的代碼加載的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; 

我希望我解釋得很好。對不起,我英語不好。

謝謝。

回答

0

您可以只添加「IMEX = 1」到您的連接字符串像↓

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

這將forceably讀取爲字符串的所有值。

0

嘗試在導入之前將所有單元格格式化爲Excel表格中的文本。 (你可以手動或編程方式做)