ASP.NET is exported to Excel using DataSet

  • 2020-05-30 19:48:28
  • OfStack

 / Read temporary file  
   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%'"); 

   // At the same time will virtual directory under Data As a temporary file directory.  
   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; 
   // Building a table structure  
   objCmd.CommandText = @"CREATE TABLE Sheet1( Equipment code  varchar, The name of the  varchar,  specifications  varchar)"; 
   // Create the insertion action Command 
   objCmd.CommandText = "INSERT INTO Sheet1( Equipment code ,  The name of the , specifications ) VALUES (@QCDM, @MC, @GG)";   
   objCmd.Parameters.Add(new OleDbParameter("@QCDM", OleDbType.VarChar)); 
   objCmd.Parameters.Add(new OleDbParameter("@MC", OleDbType.VarChar)); 
   objCmd.Parameters.Add(new OleDbParameter("@GG",OleDbType.VarChar)); 
   // traverse DataSet Insert the data into the newly created Excel In the file  
   foreach (DataRow row in dsBZDM.Tables[0].Rows) 
    for (int i=0; i<objCmd.Parameters.Count; i++) 
     objCmd.Parameters[i].Value = row[i]; 
   // Available to download  
   // Clear temporary files  
   HttpResponse response = HttpContext.Current.Response; 
   // Prepare for output  
   response.WriteFile(urlPath + fileName); 
   string httpHeader="attachment;filename=KCMX.Xls"; 
   response.AppendHeader("Content-Disposition", httpHeader); 
   // Clear temporary files after output  
   string strSaveDir = "../Data/"; 
   string strFile = Server.MapPath(strSaveDir + fileName).ToString(); 
   //string sss = urlPath + fileName; 
   System.IO.File.Delete(strFile);// Delete temporary file  

Related articles: