2016-09-22 98 views
0

我有三個excel文件,都具有相同的主鍵。我將這些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電子表格,但僅輸出第一個數據集作爲數據表。

任何輸入表示讚賞。

回答

0

我想這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"); 
+0

這是真棒。非常感謝。我不得不扼殺列的一些數據類型,但經過一些轉換後,它工作得很完美! – dev53

0

數據集的合併,你必須指定首要的關鍵。

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); 

讓我知道是否有幫助。

0

這是怎麼回事?

抓取內容到詞典:

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); 
        } 
       } 
      }