摘要:C# 使用 OleDbConnBuilder 物件讀取 Execl
讀取 Execl 方式有很多,這邊利用 OleDbConnBuilder 物件來實做。
using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; namespace ReadExecl_OleDbConnBuilder { public partial class Form1 : Form {
public Form1() { InitializeComponent();//test } private void btnConnect_Click(object sender, EventArgs e) {
try {
// 利用 OleDbConnectionStringBuilder 物件來構建連接字串。
OleDbConnectionStringBuilder connectStringBuilder = new OleDbConnectionStringBuilder();
connectStringBuilder.DataSource = @".\訂單資料.xls";
connectStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0"; connectStringBuilder.Add("Extended Properties", "Excel 8.0"); using (OleDbConnection cn = new OleDbConnection(connectStringBuilder.ConnectionString)) {
DataSet ds = new DataSet(); OleDbCommand cmdLiming = new OleDbCommand("SELECT * FROM [$Sheet1]", cn); cn.Open();
using (OleDbDataReader drLiming = cmdLiming.ExecuteReader()) { ds.Load(drLiming, LoadOption.OverwriteChanges, new string[] { "發票" }); DataGridView1.DataSource = ds.Tables[0]; } } }
catch (Exception ex) {
MessageBox.Show(ex.Message, "請注意", MessageBoxButtons.OK, MessageBoxIcon.Stop);
} } } } |
三小俠 小弟獻醜,歡迎指教