How to import csv files in C# web application and perform validations checking
-
2010年3月22日 11:25
How to import csv file in C# web application and perform validations checking .
Please let me know the approach.
Thanks in advance.
全部回复
-
2010年3月22日 15:16
Here you go...
private void loadCsvData(string fileName) { FileInfo fileIn = new FileInfo(fileName); StreamReader reader = fileIn.OpenText(); string[] lineIn; while (!reader.EndOfStream) { lineIn = reader.ReadLine().Split(','); //Validate values here } reader.Close(); }- 已建议为答案 StLuisRey 2010年3月23日 13:39
- 已标记为答案 SamAgainModerator 2010年3月29日 4:06
-
2010年3月23日 12:45
Use ADO with the Microsoft.Jet.OLEDB provider:
private static DataTable readCSV(string filename) {
string path = System.IO.Path.GetDirectoryName(filename);
string file = System.IO.Path.GetFileName(filename);
DataTable dt = new DataTable();
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + path + "';Extended Properties='text;HDR=Yes;FMT=Delimited'")) {
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM " + file, conn);
da.Fill(dt);
}
return dt;
}- 已建议为答案 M.L. Somers 2010年3月23日 12:45
- 已标记为答案 SamAgainModerator 2010年3月29日 4:06
-
2011年1月16日 14:48How to fill all data from csv into untyped dataset?here i am not able to insert string into datetime column.it gives null if first row is datetime and next column is string .
-
2012年3月5日 18:28It is a good way, but this does not work on 64bit machine.
I prefer StreamReader with Regex. -
2012年3月5日 18:36
Maybe this helps too.
void lines(string path)
{
string quoteText = "\"";
string fieldDelimiter = ",";Regex regex = new Regex(String.Format("{0}(?<field>[^{0}]*){0}|(?<field>[^{1}]*)", quoteText, fieldDelimiter), RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);
int fieldGroupIndex = regex.GroupNumberFromName("field");
using (StreamReader csv = new StreamReader(path))
{
string lineText;
List<string> row = new List<string>();
while ((lineText = csv.ReadLine()) != null)
{
MatchCollection m = regex.Matches(lineText);
for (int i = 0; i < m.Count; i += 2)
{
row.Add(m[i].Groups[fieldGroupIndex].Value);
// check the values.
}row.Clear();
}
}
}

