標籤:excel匯入c#
//需要引入的命名空間
using System.Runtime.InteropServices;//擷取滑鼠事件
using System.IO;
using System.Data.OleDb;
//核心代碼
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();//首先根據開啟檔案對話方塊,選擇要開啟的檔案
ofd.Filter = "Excel表格|*.xlsx|Excel97-2003表格|*.xls|所有檔案|*.*";//開啟檔案對話方塊篩選器,預設顯示檔案類型
string strPath;//定義檔案路徑
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
strPath = ofd.FileName;
//string sss = ofd.SafeFileName;//擷取檔案名稱
string fileType = System.IO.Path.GetExtension(strPath);//擷取檔案的尾碼
string strCon = "";
if (fileType == ".xls")//如果為97-2003格式檔案
{
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";Extended Properties=‘Excel 8.0;HDR=YES;IMEX=1‘";
}
else//如果為2007格式檔案
{
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+strPath+";Extended Properties=‘Excel 12.0;HDR=YES;IEMX=1‘";
}
OleDbConnection conn=new OleDbConnection(strCon);
Application.DoEvents();
string strSql = "select * from [Sheet1$]";
OleDbCommand Cmd= new OleDbCommand(strSql,conn);
OleDbDataAdapter da = new OleDbDataAdapter(Cmd);
DataSet ds = new DataSet();
da.Fill(ds,"插入表");
dataGridView1.DataSource=ds.Tables[0];
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
//MessageBox.Show(sss);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);//捕捉異常
}
}
}
本文出自 “無聊生活_積極面對” 部落格,請務必保留此出處http://321331.blog.51cto.com/311331/1919852
將Excel資料匯入c#的datagridview