我正在使用C#和OleDb從Excel 2007文件中讀取數據。我使用使用Oledb讀取Excel文件 - 將Excel文件的內容僅作爲文本對待
連接字符串是:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1";
以下是來讀取Excel代碼:
private OleDbConnection con = null;
private OleDbCommand cmd = null;
private OleDbDataReader dr = null;
private OleDbDataAdapter adap = null;
private DataTable dt = null;
private DataSet ds = null;
private string query;
private string conStr;
public MainWindow()
{
this.InitializeComponent();
this.query = "SELECT * FROM [Sheet1$]";
this.conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\301591\\Desktop\\Fame.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text\"";
}
private void btnImport_Click(object sender, RoutedEventArgs e)
{
this.ImportingDataSetWay();
}
private void ImportingDataSetWay()
{
con = new OleDbConnection(conStr);
cmd = new OleDbCommand(query, con);
adap = new OleDbDataAdapter(cmd);
ds = new DataSet();
adap.Fill(ds);
this.grImport.ItemsSource = ds.Tables[0].DefaultView;
}
這裏grImport是我的WPF數據網格和我使用自動生成的列。
如何確保存儲在Excel中的內容始終以字符串形式讀取。 我不允許修改任何註冊表值來實現此目的。有沒有更好的方法來讀取excel。請指導我。如果您需要任何其他信息,請告訴我。
問候, Priyank
您的excel文件是否有標題行? – 2012-02-22 09:21:39
是的,我的頭排有 – 2012-02-22 09:57:50