有没有办法使用C#将多个数据集导出到多个Excel文件中? [英] Is there is any way to export multiple dataset into multiple excel files using C#

查看:388
本文介绍了有没有办法使用C#将多个数据集导出到多个Excel文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码,用于将多个数据集导出到多个单个Excel文件。但我想要例如。我有2个数据集,按下按钮我想将test1.xlsx和第二个数据集中的第一个数据集值导出到test2.xlsx



我尝试过:



试图在点击按钮时创建两个XLWorkbook wb = new XLWorkbook()实例但仍无法获取单个文件

I have a code for exporting multiple dataset to multiple sheets of single excel file. But I want for eg. I have 2 datasets and on button click I want to export first dataset value in test1.xlsx and 2nd dataset to test2.xlsx

What I have tried:

Tried to creat two instances of XLWorkbook wb = new XLWorkbook() on button click but still not working getting single file only

推荐答案

您只是将文件写入响应缓冲区,清除缓冲区,并将相同的内容重写到响应缓冲区中。您需要在一个文件中放置多个工作表,因此您需要将所需的所有数据集传递到函数中,并将它们全部添加为单个工作表。



You're just writing a file to the response buffer, clearing the buffer, and re-writing the same thing into the response buffer. You need multiple sheets in one file, so you need to pass all the datasets that you want into the function and add them all as individual sheets.

public static void Exportds2Multiplesheets(IEnumerable<dataset> ds, string Filename)
{
   if (ds == null || ds.Tables.Count == 0) //possible null case handled
   {
      throw new ArgumentException("DataSet needs to have at least one DataTable", 
      "dataset");
   }

   HttpResponse Response = System.Web.HttpContext.Current.Response;
   string Fname = Filename + ".xlsx";

   using (XLWorkbook wb = new XLWorkbook())
   {
      foreach(var set in ds) // Add a sheet per data set
      {
         wb.Worksheets.Add(ds);
      }

      wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
      wb.Style.Font.Bold = true;

      Response.Clear();
      Response.Buffer = true;
      Response.Charset = "";
      Response.ContentType = 
         "application/vnd.openxmlformats-   officedocument.spreadsheetml.sheet";
      Response.AddHeader("content-disposition", "attachment;filename=" + Fname);

      using (MemoryStream MyMemoryStream = new MemoryStream())
      {
         wb.SaveAs(MyMemoryStream);
         MyMemoryStream.WriteTo(Response.OutputStream);

         Response.Flush();
         Response.End();
      }
   }
}
</dataset>


这篇关于有没有办法使用C#将多个数据集导出到多个Excel文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆