asp.net .NET CSV插件允许空值

ccgok5k5  于 9个月前  发布在  .NET
关注(0)|答案(4)|浏览(117)

我已经把一个CSV导入器放在一起,我假设它可以工作,虽然我得到了这个错误,我如何允许这个列为空,所以当它将它添加到表中时,它会自动设置ID?我试过:

csv.Configuration.WillThrowOnMissingFields = false;

字符串
但它不承认它,这是我尝试上传时得到的错误:
CsvHelper.ValidationException:“在索引0处找不到与”ID“]名称匹配的标头。如果您希望缺少某些标头并希望忽略此验证,请将配置HeaderValidated设置为null。您还可以更改该功能以执行其他操作,如记录问题。”

[HttpPost]
    [ActionName("CreateBulk")]
    public ActionResult CreateBulkUpload()
    {
        object db;
        var file = Request.Files["attachmentcsv"];
        using (var csv = new CsvReader(new StreamReader(file.InputStream), true))
        {
            var records = csv.GetRecords<Client>().ToList();
            foreach (var item in records)
            {
                var strip = item.homePage.Replace("https://www.", "").Replace("http://www.", "")
                    .Replace("https://", "").Replace("http://", "").Replace("www.", "");

                string[] URLtests =
                    {"https://www." + strip, "http://www." + strip, "https://" + strip, "http://" + strip};

                string[] Metric = MajesticFunctions.MajesticChecker(URLtests);
                var userId = User.Identity.GetHashCode();
                var UserTableID = 1;

                var newclient = new Client

                {
                    clientN = item.clientN,
                    homePage = Metric[0],
                    clientEmail = item.clientEmail,
                    monthlyQuota = item.monthlyQuota,
                    TrustFlow = Int32.Parse(Metric[1]),
                    CitationFlow = Int32.Parse(Metric[2]),
                    RI = Int32.Parse(Metric[3]),
                    MJTopicsID = item.MJTopicsID,
                    UserTableID = UserTableID
                };
                ViewBag.newdomain = newclient;
                return RedirectToAction("Index");
            }
        }
        return RedirectToAction("Index");

    }

gk7wooem

gk7wooem1#

The developer made some breaking changes this year,所以接受的答案将不再起作用。
相反,你必须提前创建一个配置对象,并将其注入构造函数:

var config = new CsvConfiguration(CultureInfo.InvariantCulture)
  {
     HeaderValidated = null
  };
using (var reader = new StreamReader(file))
using (var csv = new CsvReader(reader, config))

字符串

9o685dep

9o685dep2#

你尝试了错误消息中提到的建议吗?像这样?

csv.configuration.HeaderValidated = null;

字符串

ax6ht2ek

ax6ht2ek3#

确保包含这两行:

csv.Configuration.HeaderValidated = null;

csv.Configuration.MissingFieldFound = null;

字符串

beq87vna

beq87vna4#

根据开发人员所做的更改,接受的答案将不再有效,这使得必须将所需的CultureInfo参数添加到使用CultureInfo的任何类中。

更改日志:https://joshclose.github.io/CsvHelper/change-log/

因此,接下来你必须首先创建一个CSV配置,并将其注入到构造函数中,如下所示:

var config = new CsvConfiguration(CultureInfo.InvariantCulture)
  {
     HeaderValidated = null,
     MissingFieldFound = null
  };
using (var reader = new StreamReader(file))
using (var csv = new CsvReader(reader, config))

字符串

**注意:**以上两项配置必须设置为空

相关问题