Dear Imar,
to make things a bit more complete, I've given my users the option to chose between downloading the files as text file and downloading as Excel file. So why not share it here. The code is based on a short article by Eric Smith (
http://www.codeguru.com/csharp/.net/...cle.php/c12659).
First I created a addional radiobuttonlist in the aspx page and an if clause in the code behind
Code:
<%--aspx code--%>
<asp:RadioButtonList ID="rblFormaat" runat="server">
<asp:ListItem Value="excel">As Excel file</asp:ListItem>
<asp:ListItem Value="text">As text file</asp:ListItem>
</asp:RadioButtonList></td></tr>
// code behind
protected void btnSubmit_Click(object sender, EventArgs e)
{
Label1.Text = ddScaNaam.SelectedValue;
foreach (ListItem item in rblExport.Items)
{
if (item.Selected == true)
{
string connectionString = WebConfigurationManager.ConnectionStrings["ScaDatabaseConnectionString"].ConnectionString;
string filename = "";
if (rblFormaat.Text == "text")
{
// see code in previous post
}
else if (rblFormaat.Text == "excel")
{
Response.Redirect("ExportExcel.aspx?filename=" + filename);
}
}
}
}
In case the user chooses to download as Excel file, the code redirects to a page without HTML; otherwise you won't catch the file. The page without HTML only contains a page directive:
Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportExcel.aspx.cs" Inherits="ExportExcel" %>
// code behind
protected void Page_Load(object sender, EventArgs e)
{
string filename = Request.QueryString["filename"];
string connectionString = WebConfigurationManager.ConnectionStrings["ScaDatabaseConnectionString"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM " + filename, 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");
}
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename+".xls");
}
}
Hans