【问题标题】:Combine/Merge Datasets From Multiple Excel Files合并/合并来自多个 Excel 文件的数据集
【发布时间】:2017-01-31 01:55:55
【问题描述】:

我有三个 excel 文件,它们都具有相同的主键。我正在将这些 excel 文件上传到我的应用程序中,并希望将它们全部合并到一个数据集/数据表中(无论哪个更容易)。我尝试了几件事,但都没有成功。

这是我目前正在尝试的...

    [HttpPost]
    public async Task<ActionResult> Index(ICollection<IFormFile> files)
    {
        var uploads = Path.Combine(_environment.WebRootPath, "uploads");

        DataSet ds = new DataSet();
        IExcelDataReader reader = null;
        DataTable dt = new DataTable();

        foreach (var file in files)
        {

            Dataset ds2 = null;

            if (file == null || file.Length == 0)
            {
                ViewBag.Error = "Please Select An Excel File<br>";
                return View("Index");
            }
            else
            {
                using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    await file.CopyToAsync(fileStream);

                    if (file.FileName.EndsWith("xls"))
                    {
                        reader = ExcelReaderFactory.CreateBinaryReader(fileStream);                       
                    }
                    else if (file.FileName.EndsWith("xlsx"))
                    {
                        reader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
                    }
                    else
                    {
                        ViewBag.Error = "File type is incorrect<br>";
                        return View("Index");
                    }

                    reader.IsFirstRowAsColumnNames = true;                      
                    //set the second dataset as the value of the excel data
                    ds2 = reader.AsDataSet();

                    //merge the second dataset with the first...
                    ds.Merge(ds2);
                }                                      
             }                
        }

        dt = ds.Tables[0];

        return View("Index", dt);
    }  

我需要指定数据集的主键吗?目前,它正在遍历我的所有三个 excel 电子表格,但仅将第一个数据集作为数据表输出。

感谢任何输入。

【问题讨论】:

    标签: c# asp.net datatable dataset


    【解决方案1】:

    我猜IExcelDataReader.AsDataSet 只会将 excel 行读入DataRows 并将它们添加到DataTable,但没有定义真正的主键,然后DataSet/DataTable.Merge 只会附加行而不实际合并它们。

    那么你可以在这里使用我的方法来合并表格:

    Combining n DataTables into a Single DataTable

    所以剩下的代码是:

    var tables = new List<DataTable>();
    foreach (var file in files)
    {
                // ....
                tables.Add(reader.AsDataSet().Tables[0]);
                // ...
    }
    
    DataTable mergedTables = tables.MergeAll("PimaryKeyColumnName");
    

    【讨论】:

    • 这太棒了。太感谢了。我不得不弄乱列的一些数据类型,但经过一些转换,它工作得很好!
    【解决方案2】:

    要合并数据集,您必须指定主键。

    ds.Tables[0].PrimaryKey = new DataColumn[] { ds.Tables[0].Columns["pri_key"] };
    ds2.Tables[0].PrimaryKey = new DataColumn[] { ds2.Tables[0].Columns["pri_key"] };
    ds.Merge(ds2);
    

    如果有帮助,请告诉我。

    【讨论】:

      【解决方案3】:

      这个呢?

      将内容抓取到字典中:

      private Dictionary<string, string> LoadFile(string path)
              {
                  string line;
                  Dictionary<string, string> vals = new Dictionary<string, string>();
                  using (StreamReader file = new StreamReader(path))
                  {
                      while ((line = file.ReadLine()) != null)
                      {
                          string[] parts = line.Split(',');
                          vals.Add(parts[0], parts[1]);
                      }
                  }
                  return vals;
              }
      

      然后在你的程序中,加载每个文件并合并

      Dictionary<string, string> fileAValues = LoadFile(@"C:\Temp\FileA.txt");
      Dictionary<string, string> fileBValues = LoadFile(@"C:\Temp\FileB.txt");
      
                  using (StreamWriter sr = new StreamWriter(@"C:\Temp\FileC.txt"))
                  {
                      foreach (string key in fileAValues.Keys)
                      {
                          if (fileBValues.ContainsKey(key))
                          {
                              string combined = key + "," + 
      
                                String.Join(",", fileAValues[key].ToString(),
                              fileBValues[key].ToString());  
                              sr.WriteLine(combined);
                          }
                      }
                  }
      

      【讨论】:

        猜你喜欢
        • 2021-08-21
        • 2016-09-27
        • 1970-01-01
        • 2020-04-16
        • 1970-01-01
        • 2018-09-11
        • 1970-01-01
        • 2017-10-17
        • 1970-01-01
        相关资源
        最近更新 更多