2014-03-02 214 views
2

你好,我們從學校得到了一個項目。它從Excel中獲取數據並將其放到datagridview中。我得到和excel文件命名爲「data.xls」,並在一個工作表名稱「粘土」;我的代碼得到說他們找不到粘土。任何評論...這裏是我的代碼使用asp.net從excel文件獲取數據到datagridview

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Data.OleDb; 

namespace WindowsFormsApplication3 
{ 
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     String filePath = textPath.Text; 
     String sheetName = textSheet.Text; 
     string constr= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;'"; 
     OleDbConnection con = new OleDbConnection(constr); 
     OleDbDataAdapter sda = new OleDbDataAdapter("Select * from ['" + sheetName + "$']",con); 
     DataTable dt = new DataTable(); 
     sda.Fill(dt); 
     dataGridView1.DataSource = dt; 
    } 
} 
} 

回答

2

我不認爲你需要使用單引號與sheetName

用此代替;

OleDbDataAdapter sda = new OleDbDataAdapter("Select * from [" + sheetName + "$]",con); 
+0

非常感謝你@soner我認爲它需要基於一些書籍即時閱讀。先生非常感謝您。 – rein

+0

@ user3369902你很受歡迎。 –