CsvUtils.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. using System;
  2. using System.ComponentModel;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Data;
  6. using System.Data.Common;
  7. using System.IO;
  8. using System.Net;
  9. using FastReport.Utils;
  10. using System.Globalization;
  11. using System.Collections;
  12. namespace FastReport.Data
  13. {
  14. internal static class CsvUtils
  15. {
  16. /// <summary>
  17. /// The default field name.
  18. /// </summary>
  19. public const string DEFAULT_FIELD_NAME = "Field";
  20. private static void DetermineTypes(List<string[]> lines, DataTable table, NumberFormatInfo numberInfo, NumberFormatInfo currencyInfo, DateTimeFormatInfo dateTimeInfo)
  21. {
  22. int intTemp;
  23. double doubleTemp;
  24. decimal decimalTemp;
  25. DateTime dateTemp;
  26. for (int i = 0; i < table.Columns.Count; i++)
  27. {
  28. // gather types here
  29. Dictionary<Type, int> types = new Dictionary<Type, int>();
  30. // check all values in the column
  31. for (int j = 0; j < lines.Count; j++)
  32. {
  33. if (i >= lines[j].Length)
  34. {
  35. // number of values is less than number of table columns. Reasons: wrong separator or bad-formed csv file?
  36. // just skip this line
  37. }
  38. else
  39. {
  40. string value = lines[j][i];
  41. if (!String.IsNullOrEmpty(value))
  42. {
  43. if (Int32.TryParse(value, out intTemp))
  44. {
  45. types[typeof(Int32)] = 1;
  46. }
  47. else if (value.Contains(currencyInfo.CurrencySymbol) && Decimal.TryParse(value, NumberStyles.Currency, currencyInfo, out decimalTemp))
  48. {
  49. types[typeof(Decimal)] = 1;
  50. }
  51. else if (Double.TryParse(value, NumberStyles.Number, numberInfo, out doubleTemp))
  52. {
  53. types[typeof(Double)] = 1;
  54. }
  55. else if (DateTime.TryParse(value, dateTimeInfo, DateTimeStyles.NoCurrentDateDefault, out dateTemp))
  56. {
  57. types[typeof(DateTime)] = 1;
  58. }
  59. else
  60. {
  61. types[typeof(String)] = 1;
  62. break;
  63. }
  64. }
  65. }
  66. }
  67. // cases allowed:
  68. // - single type -> the type
  69. // - mix of ints and doubles -> double
  70. // - all others should not be mixed -> string
  71. Type guessType = typeof(String);
  72. if (types.Count == 1)
  73. {
  74. // get a single value this way
  75. foreach (Type t in types.Keys)
  76. {
  77. guessType = t;
  78. }
  79. }
  80. else if (types.Count == 2 && types.ContainsKey(typeof(Int32)) && types.ContainsKey(typeof(Double)))
  81. {
  82. guessType = typeof(Double);
  83. }
  84. table.Columns[i].DataType = guessType;
  85. }
  86. }
  87. internal static List<string> ReadLines(CsvConnectionStringBuilder builder, int maxLines = 0)
  88. {
  89. if (String.IsNullOrEmpty(builder.CsvFile) || String.IsNullOrEmpty(builder.Separator))
  90. return null;
  91. ServicePointManager.Expect100Continue = true;
  92. ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
  93. WebRequest request;
  94. WebResponse response = null;
  95. Uri uri = new Uri(builder.CsvFile);
  96. try
  97. {
  98. // fix for datafile in current folder
  99. if (File.Exists(builder.CsvFile))
  100. {
  101. builder.CsvFile = Path.GetFullPath(builder.CsvFile);
  102. if (uri.IsFile)
  103. {
  104. if (Config.ForbidLocalData)
  105. throw new Exception(Res.Get("ConnectionEditors,Common,OnlyUrlException"));
  106. request = (FileWebRequest)WebRequest.Create(uri);
  107. request.Timeout = 5000;
  108. response = (FileWebResponse)request.GetResponse();
  109. }
  110. }
  111. else if (uri.OriginalString.StartsWith("http"))
  112. {
  113. request = (HttpWebRequest)WebRequest.Create(uri);
  114. request.Timeout = 5000;
  115. response = (HttpWebResponse)request.GetResponse();
  116. }
  117. else if (uri.OriginalString.StartsWith("ftp"))
  118. {
  119. request = (FtpWebRequest)WebRequest.Create(uri);
  120. request.Timeout = 5000;
  121. response = (FtpWebResponse)request.GetResponse();
  122. }
  123. else
  124. {
  125. throw new NullReferenceException(Res.Get("ConnectionEditors,Common,ErrorUrlException"));
  126. }
  127. }
  128. catch (NullReferenceException ex)
  129. {
  130. throw ex;
  131. }
  132. catch (Exception e)
  133. {
  134. throw e;
  135. }
  136. if (response == null)
  137. return null;
  138. List<string> lines = new List<string>();
  139. if (maxLines == 0)
  140. maxLines = int.MaxValue;
  141. // read lines
  142. using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(builder.Codepage)))
  143. {
  144. for (int i = 0; i < maxLines; i++)
  145. {
  146. string line = reader.ReadLine();
  147. // end of stream reached
  148. if (line == null)
  149. break;
  150. // skip empty lines
  151. if (!String.IsNullOrEmpty(line))
  152. lines.Add(line);
  153. }
  154. }
  155. return lines;
  156. }
  157. internal static DataTable CreateDataTable(CsvConnectionStringBuilder builder, List<string> rawLines)
  158. {
  159. if (rawLines == null)
  160. return null;
  161. // split each line to array of values
  162. List<string[]> lines = new List<string[]>();
  163. for (int i = 0; i < rawLines.Count; i++)
  164. {
  165. string line = rawLines[i];
  166. string[] values = line.Split(builder.Separator.ToCharArray());
  167. if (builder.RemoveQuotationMarks)
  168. {
  169. for (int j = 0; j < values.Length; j++)
  170. {
  171. values[j] = values[j].Trim("\"".ToCharArray());
  172. }
  173. }
  174. lines.Add(values);
  175. }
  176. if (lines.Count == 0)
  177. return null;
  178. NumberFormatInfo numberInfo = CultureInfo.GetCultureInfo(builder.NumberFormat)?.NumberFormat ?? CultureInfo.CurrentCulture.NumberFormat;
  179. NumberFormatInfo currencyInfo = CultureInfo.GetCultureInfo(builder.CurrencyFormat)?.NumberFormat ?? CultureInfo.CurrentCulture.NumberFormat;
  180. DateTimeFormatInfo dateTimeInfo = CultureInfo.GetCultureInfo(builder.DateTimeFormat)?.DateTimeFormat ?? CultureInfo.CurrentCulture.DateTimeFormat;
  181. // get table name from file name
  182. string tableName = Path.GetFileNameWithoutExtension(builder.CsvFile).Replace(".", "_");
  183. if (String.IsNullOrEmpty(tableName))
  184. {
  185. tableName = "Table";
  186. }
  187. DataTable table = new DataTable(tableName);
  188. string[] fields = lines[0];
  189. // create table columns
  190. for (int i = 0; i < fields.Length; i++)
  191. {
  192. DataColumn column = new DataColumn();
  193. column.DataType = typeof(string);
  194. // get field names from first string if needed
  195. string fieldName = fields[i].Replace("\t", "");
  196. if (builder.FieldNamesInFirstString && !table.Columns.Contains(fieldName))
  197. {
  198. column.ColumnName = fieldName;
  199. column.Caption = column.ColumnName;
  200. }
  201. else
  202. {
  203. column.ColumnName = DEFAULT_FIELD_NAME + i.ToString();
  204. column.Caption = column.ColumnName;
  205. }
  206. table.Columns.Add(column);
  207. }
  208. int startIndex = builder.FieldNamesInFirstString ? 1 : 0;
  209. // cast types of fields if needed
  210. if (builder.ConvertFieldTypes)
  211. {
  212. int number = lines.Count - startIndex;
  213. DetermineTypes(lines.GetRange(startIndex, number), table, numberInfo, currencyInfo, dateTimeInfo);
  214. }
  215. // add table rows
  216. for (int i = startIndex; i < lines.Count; i++)
  217. {
  218. if (lines[i].Length > 0)
  219. {
  220. // get values from the string
  221. fields = lines[i];
  222. // add a new row
  223. DataRow row = table.NewRow();
  224. int valuesCount = fields.Length < table.Columns.Count ? fields.Length : table.Columns.Count;
  225. for (int j = 0; j < valuesCount; j++)
  226. {
  227. string value = fields[j];
  228. if (!String.IsNullOrEmpty(value))
  229. {
  230. if (table.Columns[j].DataType == typeof(String))
  231. {
  232. row[j] = value;
  233. }
  234. else if (table.Columns[j].DataType == typeof(Int32))
  235. {
  236. row[j] = Int32.Parse(value);
  237. }
  238. else if (table.Columns[j].DataType == typeof(Decimal))
  239. {
  240. row[j] = Decimal.Parse(value, NumberStyles.Currency, currencyInfo);
  241. }
  242. else if (table.Columns[j].DataType == typeof(Double))
  243. {
  244. row[j] = Double.Parse(value, NumberStyles.Number, numberInfo);
  245. }
  246. else if (table.Columns[j].DataType == typeof(DateTime))
  247. {
  248. row[j] = DateTime.Parse(value, dateTimeInfo);
  249. }
  250. }
  251. }
  252. table.Rows.Add(row);
  253. }
  254. }
  255. return table;
  256. }
  257. }
  258. }