简体   繁体   English

使用Asp.net C#中的文件上载将特定字段从.csv导入到SQL Serverl

[英]Import Specific fields from .csv to SQL Serverl using File Upload in Asp.net C#

csv file that has 20 columns,i have uploaded that using FileUpload Control, now i want to add only one column data in database from that 20 columns, how can i achieve this.. my code is- 具有20列的csv文件,我已经使用FileUpload Control上传了该文件,现在我想从这20列中仅在数据库中添加一列数据,我该如何实现..我的代码是-

    DataTable tblReadCSV = new DataTable();
    tblReadCSV.Columns.Add("EmailId");
    string path = System.IO.Path.GetFileName(fupEmails.PostedFile.FileName);
    fupEmails.PostedFile.SaveAs(Server.MapPath("~/Contacts/" + path));
    path = Server.MapPath("~/Contacts/" + path);
    TextFieldParser csvParser = new TextFieldParser(path);
    csvParser.Delimiters = new string[] { "," };
    csvParser.TrimWhiteSpace = true;
    //csvParser.ReadLine();
    while (!csvParser.EndOfData)
    {
        string[] fields = csvParser.ReadFields();
        tblReadCSV.Rows.Add(fields.);
    }
    string connection = @"Data Source=ANURAG-PC; Initial Catalog=MailServer; Persist Security Info=True; User ID=xx; Password=xxxxxx";
    string strSql = "Insert into EmailData(EmailId) Values(@Email)";
    SqlConnection con=new SqlConnection(connection);
    SqlCommand cmd=new SqlCommand();
    cmd.CommandType=CommandType.Text;
    cmd.CommandText=strSql;
    cmd.Connection=con;
    cmd.Parameters.Add("@Email",SqlDbType.NVarChar,250,"EmailId");
    SqlDataAdapter daAdapter=new SqlDataAdapter();
    daAdapter.InsertCommand=cmd;
    int result=daAdapter.Update(tblReadCSV);
    lblError.Text="Send Successfully";

and the problem is in these three lines- 问题出在这三行中

while (!csvParser.EndOfData)
{
    string[] fields = csvParser.ReadFields();
    tblReadCSV.Rows.Add(fields.Equals("Email");
}

here fields contains all the column headings so i just want only one field Email from the whole,how can i achieve this, above lines are not working for this. 这里的字段包含所有列标题,所以我只希望从整体发送一个字段,我该如何实现呢,上面的行对此不起作用。

You need to create a DataRow that matches the schema of you data table, and then insert the correct value from your parsed line of CSV values into that row, and then add the row to the DataTable . 您需要创建一个与数据表的架构匹配的DataRow ,然后将已解析的CSV值行中的正确值插入该行,然后将该行添加到DataTable Roughly something like the following 大致如下所示

while (!csvParser.EndOfData)
{
    var fields = csvParser.ReadFields();
    var row = tblReadCSV.NewRow();
    row["EmailId"] = fields[ordinalPositionOfEmailField];
    tblReadCSV.Rows.Add(row)
}

Put following line before your while loop 将以下行放在while循环之前

var FirstRowfields = csvParser.ReadFields();
while(!csvParser.EndOfData)
{
  //your code
}

This will read first line and then start your loop will start reading from second line so you will not heading column 这将读取第一行,然后开始循环,将从第二行开始读取,因此您不会向列标题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM