我想知道如何读取由控件上传的 csv 文件。我试过使用 OLEDB,但出现异常。关于该文件是只读的。任何帮助表示赞赏。谢谢
最佳答案
你可以试试 FileHelpers library .
下面是使用 FileUpload 控件的示例:
[DelimitedRecord(",")] // comma separated values
[IgnoreFirst(1)] // first line is assumed to be the header
[IgnoreEmptyLines] // ignore empty lines
class MyClass {
[FieldTrim(TrimMode.Both)]
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string FirstName;
[FieldTrim(TrimMode.Both)]
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string LastName;
}
protected void Button1_Click(object sender, EventArgs e) {
if (!FileUpload1.HasFile) {
// No CSV file selected
return
}
using (StreamReader sr = new StreamReader(FileUpload1.PostedFile.InputStream)) {
FileHelperEngine engine = new FileHelperEngine(typeof(MyClass));
foreach (MyClass entry in engine.ReadStream(sr)) {
// do something
}
}
}
关于c# - 使用 asp.net c# 读取上传的 .csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7673292/