protected void shang_Click(object sender, EventArgs e)
{
string filename = this.FileUpload1.FileName.Trim();
if (!filename.EndsWith(".txt"))
{
Page.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('只能导入txt文档')</script>");
return;
}
string path = Server.MapPath("./");
if (!Directory.Exists(path + "wenj"))
{
Directory.CreateDirectory(path + "wenj");
}
string paths = path + "wenj\\" + filename;
FileUpload1.PostedFile.SaveAs(paths);
// FileUpload1.SaveAs(paths);
DataSet ds = SqlDatasetTxt(DataconnectionTxt(path+"wenj"), "select * from " + FileUpload1.FileName.Trim());
this.GridView1.DataSource = ds.Tables[0];
this.GridView1.DataBind();
}
public OleDbConnection DataconnectionTxt(string txtfolder)
{
string _dBconnstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtfolder + ";Extended Properties='text;HDR=no;FMT=Delimited';";
var txtconnection = new OleDbConnection(_dBconnstring);
try
{
txtconnection.Open();
return txtconnection;
}
catch (Exception)
{
throw new Exception("無法連接給出的目錄,請重新確定路徑的正確性!");
}
}
public DataSet SqlDatasetTxt(OleDbConnection oleDbConnection, string sqlstr)
{
var tempdateset = new DataSet();
try
{
var oleDbCommand = new OleDbCommand(sqlstr, oleDbConnection);
var oleDbDataAdapter = new OleDbDataAdapter(oleDbCommand);
oleDbDataAdapter.Fill(tempdateset);
return tempdateset;
}
catch (Exception exception)
{
if (oleDbConnection.State != ConnectionState.Closed)
{
oleDbConnection.Close();
}
throw new Exception(exception.Message);
}
finally
{
oleDbConnection.Close();
}
}