復制代碼 代碼如下:
/讀取臨時文件
GYYW.DA.Common.Base_SqlDataBase daBZDM = new GYYW.DA.Common.Base_SqlDataBase();
DataSet dsBZDM = daBZDM.GetDataSetBySql("select QCDM,MC,GG from WG_BZDM where QCDM like '02%'");
//同時將虛擬目錄下的Data作為臨時文件目錄。
string urlPath = HttpContext.Current.Request.ApplicationPath + "/Data/";
string physicPath = HttpContext.Current.Server.MapPath(urlPath);
//string fileName = Guid.NewGuid() + ".Xls";
string fileName ="DownLoad.Xls";
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + physicPath + fileName +";Extended Properties=Excel 8.0;";
OleDbConnection objConn = new OleDbConnection(connString);
OleDbCommand objCmd = new OleDbCommand();
objCmd.Connection = objConn;
objCmd.Connection.Open();
//建立表結構
objCmd.CommandText = @"CREATE TABLE Sheet1(器材代碼 varchar,名稱 varchar, 規格 varchar)";
objCmd.ExecuteNonQuery();
//建立插入動作的Command
objCmd.CommandText = "INSERT INTO Sheet1(器材代碼, 名稱,規格) VALUES (@QCDM, @MC, @GG)";
objCmd.Parameters.Clear();
objCmd.Parameters.Add(new OleDbParameter("@QCDM", OleDbType.VarChar));
objCmd.Parameters.Add(new OleDbParameter("@MC", OleDbType.VarChar));
objCmd.Parameters.Add(new OleDbParameter("@GG",OleDbType.VarChar));
//遍歷DataSet將數據插入新建的Excel文件中
foreach (DataRow row in dsBZDM.Tables[0].Rows)
{
for (int i=0; i<objCmd.Parameters.Count; i++)
{
objCmd.Parameters[i].Value = row[i];
}
objCmd.ExecuteNonQuery();
}
objCmd.Connection.Close();
//提供下載
//清除臨時文件
HttpResponse response = HttpContext.Current.Response;
response.Clear();
//為輸出作准備
response.WriteFile(urlPath + fileName);
string httpHeader="attachment;filename=KCMX.Xls";
response.AppendHeader("Content-Disposition", httpHeader);
response.Flush();
//輸出完畢後清除臨時文件
string strSaveDir = "../Data/";
string strFile = Server.MapPath(strSaveDir + fileName).ToString();
//string sss = urlPath + fileName;
System.IO.File.Delete(strFile);//刪除臨時文件
response.End();