![](/img/trans.png)
[英]Compare Row of 1st Datatable with Column of 2nd Datatable and build 3rd datatable with matched columns
[英]Set 2nd row as header column in CSV to datatable conversion
我正在尝试读取CSV文件并在C#中获取数据表中的数据。
我使用了下面的代码,效果很好:
public static System.Data.DataTable GetcsvExcelRecords(string csvPath, string CSVFileName)
{
string[] workSheetNames = new string[] { };
System.Data.DataTable dtExcelData = new System.Data.DataTable();
string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + csvPath + "';Extended Properties='Text;HDR=Yes;FMT=Delimited;'";
using (OleDbConnection excelConn = new OleDbConnection(SourceConstr))
{
excelConn.Open();
OleDbCommand excelCommand = new OleDbCommand();
OleDbDataAdapter excelDataAdapter = new OleDbDataAdapter();
excelCommand = new OleDbCommand("SELECT * FROM [" + CSVFileName + "]", excelConn);
excelDataAdapter.SelectCommand = excelCommand;
excelDataAdapter.Fill(dtExcelData);
return dtExcelData;
}
}
但是,我希望第二行数据成为标题列,然后再跟随各行。 如何实现呢? 谢谢
您可以宁可使用现有的库,也不必重新发明(重新实现)...我听说FileHelpers可能有用。
无论如何,我们喜欢在意识到需要图书馆之前尝试一下。 在这种情况下...
如果csv文件大小很小,您可以尝试这样的脏事……虽然听起来很琐碎。 请注意,磁盘上需要有文件才能使用OleDbConnection ...不要忘记删除创建的文件...
public static System.Data.DataTable GetcsvExcelRecords(string csvPath, string CSVFileName)
{
string modCSVFileName = CreateFileRemovingFirstLine(csvPath, CSVFileName);
string[] workSheetNames = new string[] { };
System.Data.DataTable dtExcelData = new System.Data.DataTable();
string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + csvPath + "';Extended Properties='Text;HDR=Yes;FMT=Delimited;'";
using (OleDbConnection excelConn = new OleDbConnection(SourceConstr))
{
excelConn.Open();
OleDbCommand excelCommand = new OleDbCommand();
OleDbDataAdapter excelDataAdapter = new OleDbDataAdapter();
excelCommand = new OleDbCommand("SELECT * FROM [" + modCSVFileName + "]", excelConn);
excelDataAdapter.SelectCommand = excelCommand;
excelDataAdapter.Fill(dtExcelData);
return dtExcelData;
}
}
private static string CreateFileRemovingFirstLine(string csvPath, string CSVFileName)
{
string filePath = Path.Combine(csvPath, CSVFileName);
string modifiedFileName = CSVFileName.Replace(".csv", "2.csv");
using (StreamReader sr = new StreamReader(filePath))
{
string headerLine = sr.ReadLine();
string str = sr.ReadToEnd();
// use the appropriate encoding... for example I am using ASCII
byte[] buffer = Encoding.ASCII.GetBytes(str);
MemoryStream ms = new MemoryStream(buffer);
// write to file... check for access permission to create file
FileStream file = new FileStream(Path.Combine(csvPath, modifiedFileName), FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
}
return modifiedFileName;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.