diff --git a/src/MiniExcel/Csv/CsvReader.cs b/src/MiniExcel/Csv/CsvReader.cs index 0a89b91..9695eb7 100644 --- a/src/MiniExcel/Csv/CsvReader.cs +++ b/src/MiniExcel/Csv/CsvReader.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; +using System.Text.RegularExpressions; namespace MiniExcelLibs.Csv { @@ -22,15 +23,13 @@ namespace MiniExcelLibs.Csv using (var reader = cf.GetStreamReaderFunc(_stream)) { - char[] seperators = { cf.Seperator }; - var row = string.Empty; string[] read; var firstRow = true; Dictionary headRows = new Dictionary(); while ((row = reader.ReadLine()) != null) { - read = row.Split(seperators, StringSplitOptions.None); + read = Split(cf, row); //header if (useHeaderRow) @@ -72,15 +71,14 @@ namespace MiniExcelLibs.Csv Dictionary idxProps = new Dictionary(); using (var reader = cf.GetStreamReaderFunc(_stream)) { - char[] seperators = { cf.Seperator }; - var row = string.Empty; string[] read; //header { row = reader.ReadLine(); - read = row.Split(seperators, StringSplitOptions.None); + read = Split(cf, row); + var props = Helpers.GetExcelCustomPropertyInfos(type, read); var index = 0; foreach (var v in read) @@ -94,7 +92,7 @@ namespace MiniExcelLibs.Csv { while ((row = reader.ReadLine()) != null) { - read = row.Split(seperators, StringSplitOptions.None); + read = Split(cf, row); //body { @@ -119,5 +117,12 @@ namespace MiniExcelLibs.Csv } } } + + private static string[] Split(CsvConfiguration cf, string row) + { + return Regex.Split(row, $"[\t{cf.Seperator}](?=(?:[^\"]|\"[^\"]*\")*$)") + .Select(s => Regex.Replace(s.Replace("\"\"", "\""), "^\"|\"$", "")).ToArray(); + //this code from S.O : https://stackoverflow.com/a/11365961/9131476 + } } } diff --git a/tests/MiniExcelTests/MiniExcelIssueTests.cs b/tests/MiniExcelTests/MiniExcelIssueTests.cs index 25daa99..964d1f6 100644 --- a/tests/MiniExcelTests/MiniExcelIssueTests.cs +++ b/tests/MiniExcelTests/MiniExcelIssueTests.cs @@ -28,6 +28,27 @@ namespace MiniExcelLibs.Tests this.output = output; } + /// + /// Csv Query split comma not correct #237 + /// https://github.com/shps951023/MiniExcel/issues/237 + /// + [Fact] + public void Issue237() + { + var value = new[] + { + new{ id="\"\"1,2,3\"\""}, + new{ id="1,2,3"}, + }; + var path = PathHelper.GetNewTemplateFilePath("csv"); + MiniExcel.SaveAs(path, value); + + var rows = MiniExcel.Query(path,true).ToList(); + + Assert.Equal("\"\"1,2,3\"\"", rows[0].id); + Assert.Equal("1,2,3", rows[1].id); + } + /// /// SaveAs support multiple sheets #234 ///