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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
//定義OleDb======================================================
//1.檔案位置 注意絕對路徑 -> 非 \ 是 \\
private const string FileName = "C:\\Users\\user\\documents\\visual studio 2010\\Projects\\WindowsFormsApplication1\\WindowsFormsApplication1\\Data\\Book1.xlsx";
//2.提供者名稱 Microsoft.Jet.OLEDB.4.0適用於2003以前版本,Microsoft.ACE.OLEDB.12.0 適用於2007以後的版本處理 xlsx 檔案
private const string ProviderName = "Microsoft.ACE.OLEDB.12.0;";
//3.Excel版本,Excel 8.0 針對Excel2000及以上版本,Excel5.0 針對Excel97。
private const string ExtendedString = "'Excel 8.0;";
//4.第一行是否為標題
private const string Hdr = "Yes;";
//5.IMEX=1 通知驅動程序始終將「互混」數據列作為文本讀取
private const string IMEX = "0';";
//=============================================================
//連線字串
string cs =
"Data Source=" + FileName + ";" +
"Provider=" + ProviderName +
"Extended Properties=" + ExtendedString +
"HDR=" + Hdr +
"IMEX=" + IMEX;
//Excel 的工作表名稱 (Excel左下角有的分頁名稱)
string SheetName = "Sheet1";
public Form1()
{
InitializeComponent();
//呼叫FileLoad
FileLoad();
}
private void FileLoad()
{
using (OleDbConnection cn = new OleDbConnection(cs))
{
cn.Open();
string qs = "select * from[" + SheetName + "$]";
try
{
using (OleDbDataAdapter dr = new OleDbDataAdapter(qs, cn))
{
DataTable dt = new DataTable();
dr.Fill(dt);
this.dataGridView1.DataSource = dt;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
平台 : VS2010上編譯正常
EXECEL : 使用2007版本
EXECEL : 使用2007版本
文章標籤
全站熱搜
