Code Import Excel C#

protected string CurrentPage
{
get
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(this.Page.Request.PhysicalPath);
return fileInfo.Name;
}
}
private OleDbConnection exConn;//ติดต่อ Excel
private DataTable dt = null;//Table เก็บข้อมูล Excel
private string strConn;

protected void Page_Load(object sender, EventArgs e)
{

if (!Page.IsPostBack)
{
SetHeader(“อัพโหลดข้อมูล”);

}
}
protected void SetHeader(string header)
{
Label lblHeader = this.Master.FindControl(“lblHeader”) as Label;
lblHeader.Text = header;
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.Visible = false;
Label5.Text = “”;
string file;
if (FileUpload1.HasFile)
{
file = FileUpload1.FileName;
if (FileUpload1.FileName.LastIndexOf(“.”) != -1 && FileUpload1.FileName.Substring(FileUpload1.FileName.LastIndexOf(“.”) + 1, 3) == “xls”)
{

FileUpload1.PostedFile.SaveAs(Server.MapPath(“..\\Uploads\\Employee\\”) + file);

this.Label1.ForeColor = this.Label4.ForeColor;
//Label1.Text = “File Saved to: ” + Server.MapPath(“..\\Uploads\\Personal\\”) + file;

ShowDatatoGrid(file);

FileInfo TheFile = new FileInfo(MapPath(“..\\Uploads\\Employee\\”) + file);
if (TheFile.Exists)
{
File.Delete(MapPath(“..\\Uploads\\Employee\\”) + file);
}
}
else
{
Label2.Text = “”;
Label5.Text = “”;
this.Label1.ForeColor = this.Label3.ForeColor;
this.Label1.Text = “ไฟล์ข้อมูลที่ต้องการอัพโหลด ต้องอยู่ในรูปแบบ Excel (.xls)”;
}

}
else
{
Label2.Text = “”;
Label5.Text = “”;
this.Label1.ForeColor = this.Label3.ForeColor;
this.Label1.Text = “กรุณาเลือกไฟล์เพื่ออัพโหลด”;
}
}
private void ShowDatatoGrid(string f)
{

try
{
GridView1.Visible = true;

this.strConn = @”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + Server.MapPath(“..\\Uploads\\Employee\\”) + f + @”;Extended Properties=””Excel 8.0;”””;

this.GridView1.DataSource = getWorksheet(“Sheet1$”);

this.GridView1.DataBind();

Label2.Text = “ข้อมูลทั้งหมด : ” + this.GridView1.Rows.Count + ” คน”;

}

catch (Exception ex)
{
this.Label1.ForeColor = this.Label3.ForeColor;
this.Label1.Text = ex.Message;

}

}
private DataTable getWorksheet(string worksheet)
{

DataSet m_ds = new DataSet();

try
{

exConn = new OleDbConnection(strConn);

exConn.Open();

OleDbDataAdapter m_da = new OleDbDataAdapter(“SELECT * FROM [” + worksheet + “] “, exConn);

m_da.Fill(m_ds, “Table”);

}

catch (Exception ex)
{
this.Label1.ForeColor = this.Label3.ForeColor;
this.Label1.Text = ex.Message + “”;

}

finally
{

exConn.Close();

}

if (m_ds.Tables.Count > 0)
{

return m_ds.Tables[0];

}

else
{

dt = new DataTable();

return dt;

}
}