{
openFileDialog1.Filter = "Excel文件(*.xlsx,*.xls)|*.xlsx;*xls";
//openFileDialog1.InitialDirectory = path;//指定初始化路径
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
ExecelFilePath.Text = openFileDialog1.FileName;
}
}
private void Form1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Link;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void Form1_DragDrop(object sender, DragEventArgs e)
{
string GetDragFileName = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
if (GetDragFileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase))
{
ExecelFilePath.Text = GetDragFileName;
DataSet ds = ExcelToDataSet(GetDragFileName);
ShowExcel.DataSource = ds.Tables[0];
}
}
记得引用 excel 处理类库
/// <summary>
/// 读取Excel文件,将内容存储在DataSet中
/// </summary>
/// <param name="opnFileName">带路径的Excel文件名</param>
/// <returns>DataSet</returns>
private DataSet ExcelToDataSet(string opnFileName)
{
string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + opnFileName + ";Extended Properties=\"Excel 12.0;HDR=YES\"";
if (opnFileName.EndsWith(".xls", StringComparison.OrdinalIgnoreCase))
{
strCon = " Provider = Microsoft.Jet.OLEDB.4.0; Data Source =" + opnFileName + ";Extended Properties=Excel 8.0";
}
OleDbConnection myConn = new OleDbConnection(strCon);
string strCom = " SELECT * FROM [Sheet1$]";
myConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet, "[Sheet1$]");
myConn.Close();
return myDataSet;
}