1 using Microsoft.VisualBasic.FileIO;
4 using System.Collections.Generic;
8 using System.Threading.Tasks;
10 namespace Sage.ES.S50.Extensions
12 public static class ExtensionsDataTable
14 public static void ImportCSV(
this DataTable dataTable,
string csvFile,
string separator =
";",
bool hasFieldsEnclosedInQuotes =
true,
bool primeraFilaDatos =
true)
18 bool assignedTypes =
false;
19 using (TextFieldParser csvReader =
new TextFieldParser(csvFile))
21 csvReader.SetDelimiters(separator);
22 csvReader.HasFieldsEnclosedInQuotes = hasFieldsEnclosedInQuotes;
23 string[] colFields = csvReader.ReadFields();
24 foreach (
string column
in colFields)
26 DataColumn dataColumn =
new DataColumn(column)
30 dataTable.Columns.Add(dataColumn);
32 while (!csvReader.EndOfData)
34 string[] fieldData = csvReader.ReadFields();
35 List<object> fieldList =
new List<object>();
36 for (
int i = 0; i <= fieldData.Length - 1; i++)
39 if (
int.TryParse(fieldData[i].ToString(), out
int resultInt))
41 fieldList.Add(resultInt);
44 dataTable.Columns[i].DataType = typeof(
int);
47 else if (DateTime.TryParse(fieldData[i].ToString(), out DateTime resultDateTime))
49 fieldList.Add(resultDateTime);
52 dataTable.Columns[i].DataType = typeof(DateTime);
55 else if (fieldData[i].ToString() ==
"")
61 fieldList.Add(fieldData[i]);
65 dataTable.Rows.Add(fieldList.ToArray());
89 public static void ImportCSV_Idatos(
this DataTable dataTable,
string csvFile, List<CargarDatos.stInfoFields> InfoFields,
string separator =
";",
bool hasFieldsEnclosedInQuotes =
true,
bool primeraFilaDatos =
true)
93 using (TextFieldParser csvReader =
new TextFieldParser(csvFile))
95 csvReader.SetDelimiters(separator);
96 csvReader.HasFieldsEnclosedInQuotes = hasFieldsEnclosedInQuotes;
97 string[] colFields = csvReader.ReadFields();
100 foreach (
string column
in colFields)
102 DataColumn dataColumn =
new DataColumn(column)
106 dataTable.Columns.Add(dataColumn);
111 string abc =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
113 for (
int j = 0; j < colFields.Length; j++)
115 DataColumn dataColumn =
new DataColumn(abc)
119 dataTable.Columns.Add(abc.Substring(j, 1));
123 while (!csvReader.EndOfData)
125 string[] fieldData = (primeraFilaDatos ? csvReader.ReadFields() : colFields);
126 primeraFilaDatos =
true;
128 List<object> fieldList =
new List<object>();
130 for (
int i = 0; i <= fieldData.Length - 1; i++)
132 string valor = InfoFields[i].tipoColumna;
136 fieldList.Add(fieldData[i]);
137 dataTable.Columns[i].DataType = typeof(Int32);
140 fieldList.Add(fieldData[i]);
141 dataTable.Columns[i].DataType = typeof(
double);
144 if (
string.IsNullOrEmpty(fieldData[i]))
146 fieldList.Add(
false);
150 fieldList.Add(fieldData[i]);
152 dataTable.Columns[i].DataType = typeof(
bool);
155 fieldList.Add(fieldData[i]);
156 dataTable.Columns[i].DataType = typeof(DateTime);
159 if (fieldData[i].ToString() ==
"")
165 fieldList.Add(fieldData[i]);
171 dataTable.Rows.Add(fieldList.ToArray());