从多个Excel文件合并/合并数据集
问题描述:
我有三个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电子表格,但仅输出第一个数据集作为数据表。
任何输入表示赞赏。
答
我想这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");
答
数据集的合并,你必须指定首要的关键。
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);
让我知道是否有帮助。
答
这是怎么回事?
抓取内容到词典:
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);
}
}
}
这是真棒。非常感谢。我不得不扼杀列的一些数据类型,但经过一些转换后,它工作得很完美! – dev53