關鍵代碼
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == false)//HasFile用來檢查FileUpload是否有指定文件
{
Response.Write("<script>alert('請您選擇Excel文件')</script> ");
return;//當無文件時,返回
}
string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//System.IO.Path.GetExtension獲得文件的擴展名
if (IsXls != ".xls")
{
Response.Write("<script>alert('只可以選擇Excel文件')</script>");
return;//當選擇的不是Excel文件時,返回
}
string filename = FileUpload1.FileName; //獲取Execle文件名 DateTime日期函數
string savePath = Server.MapPath(("../upfiles\\") + filename);//Server.MapPath 獲得虛擬服務器相對路徑
FileUpload1.SaveAs(savePath); //SaveAs 將上傳的文件內容保存在服務器上
DataSet ds = ExcelSqlConnection(savePath, filename); //調用自定義方法
DataRow[] dr = ds.Tables[0].Select(); //定義一個DataRow數組
int rowsnum = ds.Tables[0].Rows.Count;
if (rowsnum == 0)
{
Response.Write("<script>alert('Excel表為空表,無數據!')</script>"); //當Excel表為空時,對用戶進行提示
}
else
{
for (int i = 0; i < dr.Length; i++)
{
//前面除了你需要在建立一個“upfiles”的文件夾外,其他的都不用管了,你只需要通過下面的方式獲取Excel的值,然后再將這些值用你的方式去插入到數據庫里面
string title = dr[i]["姓名"].ToString();
string linkurl = dr[i]["工號"].ToString();
string categoryname = dr[i]["性別"].ToString();
string customername = dr[i]["出生日期"].ToString();
//Response.Write("<script>alert('導入內容:" + ex.Message + "')</script>");
}
Response.Write("<script>alert('Excle表導入成功!');</script>");
}
}
/// <summary>
/// 連接Excel 讀取Excel數據 並返回DataSet數據集合
/// </summary>
/// <param name="filepath">Excel服務器路徑</param>
/// <param name="tableName">Excel表名稱</param>
/// <returns></returns>
public static DataSet ExcelSqlConnection(string filepath, string tableName)
{
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
OleDbConnection ExcelConn = new OleDbConnection(strCon);
try
{
string strCom = string.Format("SELECT * FROM [Sheet1$]");
ExcelConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, ExcelConn);
DataSet ds = new DataSet();
myCommand.Fill(ds, "[" + tableName + "$]");
ExcelConn.Close();
return ds;
}
catch
{
ExcelConn.Close();
return null;
}
}
下載Excel樣例

//c#標准下載文件代碼
protected void LinkButton1_Click(object sender, EventArgs e)
{
string _filepath = "~/upfiles/樣本.xls";
string _filename = "樣本.xls";
if (System.IO.File.Exists(MapPath(_filepath)))
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "attachment;filename=" + _filename);
Response.ContentType = "application/unknow";
Response.TransmitFile(_filepath);
Response.End();
}
}
測試Html
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="批量導入" onclick="Button1_Click" />
<p><asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">下載樣本示例</asp:LinkButton></p>