首先引用库Microsoft.Office.Interop.Excel
一:将Excel文件导入datagridview控件中
//缩写命名空间
using Excel=Microsoft.Office.Interop.Excel
//单击“打开文件”按钮
private void button_Click(Object sender,Eventargs e)
{
if(openfiledialog.ShowDialog()==DialogResult.OK)
{
String strpath=openfiledialog.FileName;
//调用读取Excel文件的函数
DataTable dt=ReadExcel(strpath);
//设置datagridview控件的数据源
datagridview1.DataSource=dt;
}
}
protected static DataTable ReadExcel(String strpath)
{
//设置连接字符串,舍弃表头
string strCon="provider=microsoft.jet.oledb.4.0;data source=" + strpath + ";extended properties='excel 8.0;HDR=NO;IMEX=1'";
//建立连接
OleDbConnection Con=new OleDbConnection(strCon);
//打开连接
Con.open();
String strSql="select * from [sheet1$]";
OleDbCommand Cmd=new OleDbCommand(strSql,Con);
OleDataAdapter da=new OleDataAdapter(Cmd);
DataSet ds=new DataSet();
da.Fill(ds);
Con.Close();
return ds.Tables[0];
}
二:将datagridview中的控件中的数据导出到Excel中
private