There are a few tricks to making this work. First, you have to create an ASPX page with no HTML content in it. The only thing that should be in the ASPX page is the Page directive at the top. The second trick is to clear the existing content and send down a new content type. For Excel, you use a content type of application/vnd.ms-excel. This tells your Web browser to expect something that can be handled within Excel. The third trick is to send down the data tab-delimited per column and a newline at the end of each row. After that, Excel does the rest of the work for you.
Here's the code:
protected void Page_Load(object sender, EventArgs e) { SqlConnection cn = new SqlConnection("yourconnectionstring"); cn.Open(); SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Users", cn); DataTable dt = new DataTable(); da.Fill(dt); cn.Close(); Response.Clear(); Response.ContentType = "application/vnd.ms-excel"; string sep = ""; foreach (DataColumn dc in dt.Columns) { Response.Write(sep + dc.ColumnName); sep = "\t"; } Response.Write("\n"); int i; foreach (DataRow dr in dt.Rows) { sep = ""; for (i = 0; i < dt.Columns.Count; i++) { Response.Write(sep + dr[i].ToString()); sep = "\t"; } Response.Write("\n"); } }
After I open my connection and retrieve my data, I clear the output buffer and send down a new content type, since the default type of text/HTML isn't appropriate in this case. I then loop through the columns and write out the column names, separated by tabs. At the end of the field list, I send down a newline character.
I then loop through the rows of the table and, within each row, loop through the fields. Each field value is printed out in its default format under the appropriate column header. If you have data types, such as Booleans, that should be printed in a different format, you can look at the dt.Columns collection to help determine which data type each field is and use an appropriate conversion function.
The result of running this page is a prompt to open or save the Excel spreadsheet. You can use this code with any query and any database connection. Once you've got the content cleared and the content type set, Excel does the hard work of formatting for you.
No comments:
Post a Comment