標籤:c# excel 檔案 讀取
具體的源碼如下,顯示開啟檔案瀏覽器選擇Excel檔案,對檔案進行讀取,最後展示出讀取的部分內容。
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } //添加兩個函數,一個是讀取Excel檔案的函數,另一個是寫資料進入Excel檔案的函數。 public static DataTable LoadDataFromExcel(string filePath,string sheetName) { DataSet getdata = new DataSet(); string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; string strExcel = string.Format("select * from [{0}$]",sheetName); //串連資料來源 OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); //適配到資料來源 OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn); adapter.Fill(getdata, sheetName); conn.Close(); return getdata.Tables[sheetName]; } public static void WriteDataToExcel(DataSet DS, string filePath) { } //開啟檔案瀏覽器,選擇需要的檔案 private void btnOpen_Click(object sender, RoutedEventArgs e) { OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.Multiselect = false; fileDialog.Title = "請選擇檔案"; fileDialog.Filter = "Excel file|*.xlsx"; if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string file = fileDialog.FileName; //System.Windows.Forms.MessageBox.Show("已選擇的檔案:" + file); Pathtxt.Text = file; } } private void btnTransfer_Click(object sender, RoutedEventArgs e) { DataTable FurTable = LoadDataFromExcel(Pathtxt.Text, "Nov FUR"); DataRow dtRow = FurTable.Rows[0]; object[] RowItem = dtRow.ItemArray; Pathtxt.Text = ""; foreach (object item in RowItem) { if (item.ToString() != null) { Pathtxt.Text += item.ToString(); Pathtxt.Text += " "; } } //System.Windows.Forms.MessageBox.Show(dtRow[0].ToString()); } }
C#下Excel檔案的讀取