我想读一个csv文件,其中标题行从特定列名开始,即“name”
CSV文件格式如下所示:
v3,vf,gf--Not a Header row 1
v1,c,z1,e--Not a Hera row 2
name,q1,q2,q3- Header Row- row 3-because name is here
a,0,1,2-Data
我想读一下“名称”列的位置 - 所以我想跳过前两行,但我们在“名称”之前不知道将会有多少行可能是2或3或n
答案 0 :(得分:0)
逐行阅读,然后扔掉线条,直到到达所需的标题行。然后,解析剩余的行。
IEnumerable<string[]> ReadDataLines(string csv) {
using(var reader = new StringReader(csv))
using(var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(reader)) {
parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
parser.SetDelimiters(",");
// Until we find the header row, just throw away all the rows
while(!parser.EndOfData) {
var line = parser.ReadLine();
if(line != null && line.TrimStart().StartsWith("name")) {
break;
}
}
// The rest of the input is data rows
while(!parser.EndOfData) {
yield return parser.ReadFields();
}
}
}
在这里,我使用Microsoft.VisualBasic.FileIO.TextFieldParser来解析CSV(参见Reading CSV files using C#)。您当然可以使用任何想要解析CSV的技术,也可以使用相同的通用方法。
答案 1 :(得分:0)
con = new SqlConnection(strcon);
string[] arrFileName;
if (files != null && files.Length > 0)
{
arrFileName = new string[files.Length];
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FileName", "");
int Result = cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
for (int i = 0; i < files.Length; i++)
{
string FileName = string.Empty;
string filepath = files[i];
FileName = filepath.Split('\\').Last();
///////////Logic For Import File
using (StreamReader sr = new StreamReader(filepath))
{
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
dt.Columns.Add(new DataColumn("FileName"));
dt.Columns.Add(new DataColumn("Date"));
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
row = dt.NewRow();
row.ItemArray = value;
row[9] = FileName;
row[10] = DateTime.Now;
dt.Rows.Add(row);
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "InvoiceData";
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.BulkCopyTimeout = 2000;
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
//////Logic For Delete File From Folder if you want
File.Delete(filepath);
}
files = new string[] { };
txtFilePath.Text = null;
MessageBox.Show("Files Imported Successfully!!");
}
else
{
MessageBox.Show("Please Browse The File!!");
}