【问题标题】:Download multiple excel files from the DataTable从 DataTable 下载多个 excel 文件
【发布时间】: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


    【解决方案1】:

    您在创建第一个文件后调用 response.end - 这将中止其余过程。

    我认为您无法使用此方法创建 3 个 excel 文件以供下载。

    作为替代方案,您可以在磁盘上创建 3 个 CSV 文件,然后使用 zip 库将它们压缩。 见zipping files

    或者您可以将 JET 与 Excel 连接字符串一起使用,并使用 SQL Insert 语句将您的数据推送到一个空的 Excel 文件中。并为每个表格使用不同的工作表

    write to excel with JET(但这会将您限制为 32 位)

    或者您可以使用第三方控件编写一个 Excel 文件,其中三个表格作为工作表

    Infragistics excel control

    但如果我是你 - 我只会向用户展示 3 个不同的链接,他们可以点击。

    【讨论】:

      猜你喜欢
      • 2015-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 2018-12-11
      • 2019-03-24
      • 2013-07-23
      相关资源
      最近更新 更多