我想知道如何读取由控件上传的csv文件。我曾尝试使用OLEDB,但我得到一个例外。关于该文件是只读的东西。任何帮助表示赞赏。感谢
答案 0 :(得分:2)
您可以尝试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
}
}
}
答案 1 :(得分:0)
我不知道您正在获得的具体错误或您尝试过的内容,我使用类似以下的内容来读取OLED文件中的CSV文件
string sCSVConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + PATHTOFILE + @";Extended Properties='text;HDR=Yes;FMT=Delimited(,)';";
using ( OleDbConnection connection = new OleDbConnection(sCSVConnectionString))
{
connection.ConnectionString = sCSVConnectionString;
connection.Open();
using (DbCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM [" + FILENAME + "]";
using (DbDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
// do something with the DataReader dr here.
}
dr.Close();
}
}
connection.Close();
}
答案 2 :(得分:0)
我曾经使用Fast CSV reader几次,确实很快。这是我在面对CSV文件时使用的。
祝你好运GJ