BrianRudloff.com

.Net Development


My Resume
WebDOCPDF
RTFODTTXT
powered by emurse

Recent comments





Exporting SQL Data to Excel Programatically (Without DTS)

The following code can be used for creating a spreadsheet on the fly and presenting it to a user for download.  It's important to note that it doesn't really create a spreadsheet on the fly... rather it copies a template sheet and then populates the copy.  Either way, to the user its transparent.  Just create a template sheet with all of your column names and store it in one of your project folders.

The code is as follows:

protected void btn_exportdata_Click(object sender, EventArgs e)

     {               
         //Creates a guid named filequid (unique identifier)
        Guid fileguid = Guid.NewGuid();
        //String the new filename  * Replace “Server_Name” & “Folder_Name”     
        string filename = @"\\Server_Name\Folder_Name\" + fileguid.ToString() + ".csv";
        
        //Create the new file and copy the template column names into it * Replace “Server_Name” & “Folder_Name”
       File.Copy(@"\\Server_Name\Folder_Name\Template.xls", filename);              
      
       //Make your database connection
        string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        SqlConnection dbConnection = new SqlConnection(cs);
        dbConnection.Open();
       
       //Create sql command
        SqlCommand export_data = dbConnection.CreateCommand();
       
       //Populate sql command * Replace “Select * from customers” with your select command
       export_data.CommandText = @"insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=" +     filename + ";', 'SELECT * FROM [Sheet1$]') select * from customers";
                    
        //Execute sql command
         export_data.ExecuteNonQuery();
       
        //Close the connection
         dbConnection.Close();
       
      //Present the spreadsheet to the user for download * Replace “sitename.com/Folder_Name” with your specifics
        Response.Redirect("http://sitename.com/Folder_Name/" + fileguid.ToString() + ".csv");
    }

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,
Categories: .net | c# | sql | excel
Posted by Brian Rudloff on Thursday, August 30, 2007 8:45 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Add comment


(Will show your Gravatar icon)  

  Country flag




Live preview

Thursday, August 28, 2008 3:18 AM

Gravatar