准备项:negut包引用 CsvHelper
webapi基于IFormCollection接收文件
var files = (FormFileCollection)formCollection.Files; if (files.Count == 0) return Failed<string>("请上传xls或者xlsx类型或者CSV的文件"); foreach (var (file, plexus) in from IFormFile file in files let plexus = FileHelper.GetPostfixStr(file.FileName).Replace(".", "").ToLower() select (file, plexus)) { if (!(plexus.Equals(FileEnum.xls.ObjToString()) || plexus.Equals(FileEnum.xlsx.ObjToString()) || plexus.Equals(FileEnum.csv.ObjToString()))) return Failed<string>("请上传xls或者xlsx类型或者csv类型的文件"); var dataDtos = new List<RemittancelistDto>(); if (plexus.Equals(FileEnum.csv.ObjToString())) { var stream = file.OpenReadStream(); TextReader textReader = new StreamReader(stream); using var csv = new CsvReader(textReader, CultureInfo.InvariantCulture); csv.Read();//开始读取文件 csv.ReadHeader(); //读取首行记录作为表头 while (csv.Read()) //逐行读取 { var record = new RemittancelistDto { OrderNo = csv.GetField("Order No."),//Excel中的字段名 OrderItemNo = csv.GetField("Order Item No."), }; dataDtos.Add(record); } } }