【发布时间】:2015-07-07 10:32:25
【问题描述】:
我正在尝试使用 for 循环执行查询。对于每个循环,它应该下载一个 excel 文件。该解决方案完美运行,但仅下载了第一个文件,而未下载其他两个文件。我还附上了下面的完整代码。
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Btn_Click(object sender, EventArgs e)
{
DataTable it = GetList();
foreach(DataRow dr in it.Rows)
{
string a = dr[0].ToString();
for (int i = 0; i < 3; i++)
{
string inm = it.Rows[i][0].ToString();
DataTable gt = GetData(inm);
ExportToSpreadsheet(gt, "Samples");
}
}
}
public DataTable GetData(string i)
{
SqlCommand command = null;
SqlConnection conn = null;
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
command = new SqlCommand("SELECT id, name, class FROM StudentTable WHERE (id = " + i + ") ORDER BY name";
DataTable dt = new DataTable();
SqlDataAdapter ada = new SqlDataAdapter(command);
ada.Fill(dt);
return dt;
}
public static void ExportToSpreadsheet(DataTable table, string name)
{
HttpContext context = HttpContext.Current;
context.Response.ClearContent();
context.Response.ContentType = "text/vnd.ms-excel";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".xls");
string tab = "";
foreach (DataColumn dc in table.Columns)
{
context.Response.Write(tab + dc.ColumnName);
tab = "\t";
}
context.Response.Write("\n");
context.Response.Write("\n");
int i;
foreach (DataRow dr in table.Rows)
{
tab = "";
for (i = 0; i < table.Columns.Count; i++)
{
context.Response.Write(tab + dr[i].ToString());
tab = "\t";
}
context.Response.Write("\n");
}
context.Response.End();
}
我看过类似的帖子。有人建议,可以在服务器上创建 zip 文件并在“zip”文件夹中下载多个 excel 文件。如果可能的话,我该如何将它实施到上述解决方案中?
【问题讨论】:
标签: asp.net datatable export-to-excel