选择按钮 得到路径
openFileDialog1.FileName = "选择您要输入得文件";
openFileDialog1.Filter = "Excel2007|*.xlsx|Excel2003|*.xls";
openFileDialog1.Title = "请选择指定格式的服务器列表文件";
openFileDialog1.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text = openFileDialog1.FileName;
}
确定按钮 导入到页面。
try
{
string strConn = "";
string filePath = openFileDialog1.FileName;
string str = filePath.Substring(filePath.LastIndexOf(".") + 1, filePath.Length - filePath.LastIndexOf(".") - 1);
if (str == "xlsx")
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + "Extended Properties=Excel 12.0;";
}
else
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source='" + filePath + "';" + "Extended Properties=Excel 8.0;";
}
OleDbConnection oleConn = new OleDbConnection(strConn);
oleConn.Open();
try
{
OleDbCommand cmd = oleConn.CreateCommand();
cmd.CommandText = string.Format(" select * from [{0}$]", "Sheet1");//[sheetName$]要如此格式
///OleDbDataReader odr = cmd.ExecuteReader();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
this.dgvCardInfo.DataSource = ds.Tables[0];
}
finally
{
oleConn.Close();
this.textBox1.Text = "选择要导入得路径";
}
}
catch (Exception ex)
{
MessageBox.Show("选择要导入得路径。");
}