我正在尝试读取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;
}
}
但是,我希望第二行数据是标题列,然后是行。怎么做到这一点? 感谢
答案 0 :(得分:0)
你可以宁愿使用现有的库而不是重新发明(重新实现)......我听说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;
}