我公司有客户线索的CSV文件,需要导入我们的CRM。我需要导入的CSV文件列按此顺序才能成功导入。在某些情况下,如果用户没有正确格式化列,则可能会出现用户错误并且名字可能首先出现。为了防止以这种方式导入整个文件,我需要检查并查看所有列是否按此顺序匹配:
到目前为止,我所掌握的并没有正确验证公司名称是否排在第一位,而只是将公司名称中的A列保存在CSV中。我已经尝试了很多相似的东西,但没有运气。我在查找代码背后的逻辑时遇到了麻烦。 注意:我写的内容不会读取列标题,我确定这就是我的问题所在。
控制器:
[HttpPost]
public ActionResult LeadProcessImport(HttpPostedFileBase FileUpload)
{
DataTable dt = new DataTable();
if (FileUpload == null)
{
TempData["Message"] = "";
return View();
}
string ext = Path.GetExtension(FileUpload.FileName);
if (FileUpload.ContentLength > 0)
{
string fileName = Path.GetFileName(FileUpload.FileName);
string path = Path.Combine(Server.MapPath("~/Content/images"), fileName);
try
{
FileUpload.SaveAs(path);
dt = ProcessCSV(path);
foreach (DataRow row in dt.Rows)
{
Lead leadImport = new Lead();
// order I need columns to appear in CSV
//
leadImport.CompanyName = row[0].ToString();
leadImport.FirstName = row[1].ToString();
leadImport.LastName = row[2].ToString();
leadImport.Title = row[3].ToString();
leadImport.Email = row[4].ToString();
leadImport.StreetAddress = row[5].ToString();
leadImport.City = row[6].ToString();
leadImport.State_Province = row[7].ToString();
leadImport.Zip_PostalCode = row[8].ToString();
leadImport.Phone = row[9].ToString();
leadImport.Mobile = row[10].ToString();
leadImport.Fax = row[11].ToString();
leadImport.WebURL = row[12].ToString();
leadImport.LeadSource = 1;
leadImport.LeadStatus = 2;
// If string "Company Name" in header does not appear
// first, dump the Datatable and return to different page
// no workie
if (leadImport.CompanyName != row[0].ToString())
{
dt.Dispose();
return Redirect(Url.Action("LeadProcess"));
}
else
// if all columns are in correct order, carry on
// with the import
{
db.Leads.Add(leadImport);
}
}
db.SaveChanges();
}
catch (Exception ex)
{
ViewData["Feedback"] = ex.Message;
}
}
else
{
ViewData["Feedback"] = "Please select a file";
}
dt.Dispose();
return Redirect(Url.Action("Index"));
}
答案 0 :(得分:0)
如果您要解析CSV,我建议您使用CsvHelper之类的工具。我们一直在使用它来完成一项非常类似的任务。它有各种很棒的配置。
var csvConfiguration = new CsvConfiguration
{
Quote = '"',
Delimiter = ",",
TrimFields = true,
TrimHeaders = true,
QuoteNoFields = false,
QuoteAllFields = false,
HasHeaderRecord = true,
IsHeaderCaseSensitive = false,
WillThrowOnMissingField = false
};
var field = csvReader.GetField("YourFieldName"),
它还有一个非常好的mapping functionality