使用ASP.NET Core MVC上传CSV数据到SQL数据库
我正在尝试将数据从.csv
文件插入我的数据库中,但是每当我上传数据时,记录都是空的。
目前
[HttpPost]
public async Task<IActionResult> ImportFromExcel(IFormFile formFile)
{
var data = new MemoryStream();
await formFile.CopyToAsync(data);
data.Position = 0;
TextReader reader = new StreamReader(data);
var csvReader = new CsvReader(reader, new CsvConfiguration(System.Globalization.CultureInfo.CurrentCulture)
{
HasHeaderRecord = true,
HeaderValidated = null,
MissingFieldFound = null
});
var Name = csvReader.GetField(0).ToString();
var dep = "cccccccccc";
var pos = "bbbbbbbbbbb";
await dcx.Participants.AddAsync(new Participant
{
Name = Name,
Position = pos,
Department = dep,
});
dcx.SaveChanges();
return ViewComponent("ViewParticipants");
}
到
I am trying to insert data from a .csv
file into my database, but anytime I upload data, the record is empty.
This is my code so far:
[HttpPost]
public async Task<IActionResult> ImportFromExcel(IFormFile formFile)
{
var data = new MemoryStream();
await formFile.CopyToAsync(data);
data.Position = 0;
TextReader reader = new StreamReader(data);
var csvReader = new CsvReader(reader, new CsvConfiguration(System.Globalization.CultureInfo.CurrentCulture)
{
HasHeaderRecord = true,
HeaderValidated = null,
MissingFieldFound = null
});
var Name = csvReader.GetField(0).ToString();
var dep = "cccccccccc";
var pos = "bbbbbbbbbbb";
await dcx.Participants.AddAsync(new Participant
{
Name = Name,
Position = pos,
Department = dep,
});
dcx.SaveChanges();
return ViewComponent("ViewParticipants");
}
This is the sample data in my database table:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要您的CSV的标题与数据库中的列的名称匹配,您就应该能够执行类似的操作。如果名称不匹配,则可以使用
.name(“ csvcolumnname”)
in参与者
在CSV文件中添加列的名称。示例:map(r =&gt; r.description).name(“ mycsvdescription”);
。As long as the headers of your CSV match up to the names of the columns in your database, you should be able to do something like this. If the names don't match, you can use
.Name("CsvColumnName")
inParticipantMap
to add the name of the column in the CSV file. Example:Map(r => r.Description).Name("MyCsvDescription");
.我认为,您应该调用
csvreader.read()
首先读取文件行。您可以参考以下测试代码,它可以正常工作。
测试结果:


In my opinion, you should call
csvReader.Read()
to read the file row first.You can refer to the following test code, it works fine.
Test Result:

