2012-02-03 4 views
0

데이터를 제어 할 수없는 .csv 파일이 있는데 무엇인가 이유로 따옴표로 묶입니다.파일 도우미에서 따옴표 제거

"Date","Description","Original Description","Amount","Type","Category","Name","Labels","Notes" 
"2/02/2012","ac","ac","515.00","a","b","","javascript://" 
"2/02/2012","test","test","40.00","a","d","c",""," " 

나는 filehelpers를 사용하고 내가 어떻게 될 모든 따옴표를 제거하는 가장 좋은 방법 궁금? "따옴표 제거가 표시되면 따옴표를 찾지 못하면 아무 것도하지 않습니다"라는 내용이 있습니까? 나는이 경우 내가 원하는 특히 이후 불필요한 여분의 따옴표 (와 "\"515.00\""있을 것이다 그것은 소수가 아닌 문자열로서

데이터 놨어요. "

나는 또한 무엇 확실하지 않다"자바 스크립트 " 에 관한 모든과가 발생하지만,이 서비스에서입니다 이유를 내가 통제 할 이상이 없다.

편집 이 내가 CSV 파일을 소비하는 방법입니다.

using (TextReader textReader = new StreamReader(stream)) 
     { 
      engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue; 

      object[] transactions = engine.ReadStream(textReader); 
     } 
+0

우리가 코드를 볼 수 있을까요? –

답변

6

당신은 FieldQuoted 속성은 속성 페이지 here에서 가장 잘 설명 할 수 있습니다. 속성은 모든 FileHelpers 필드에 적용될 수 있습니다 (입력 한 경우에도 Decimal). FileHelpers 클래스는 가져 오기 파일의 사양을 설명합니다. 따라서 Decimal 필드를 FieldQuoted으로 표시하면 파일에 이 나오고이 필드는 인용됩니다.

class Program 
{ 
    [DelimitedRecord(",")] 
    [IgnoreFirst(1)] 
    public class Format1 
    { 
     [FieldQuoted] 
     [FieldConverter(ConverterKind.Date, "d/M/yyyy")] 
     public DateTime Date; 
     [FieldQuoted] 
     public string Description; 
     [FieldQuoted] 
     public string OriginalDescription; 
     [FieldQuoted] 
     public Decimal Amount; 
     [FieldQuoted] 
     public string Type; 
     [FieldQuoted] 
     public string Category; 
     [FieldQuoted] 
     public string Name; 
     [FieldQuoted] 
     public string Labels; 
     [FieldQuoted] 
     [FieldOptional] 
     public string Notes; 
    } 

    static void Main(string[] args) 
    { 
     var engine = new FileHelperEngine(typeof(Format1)); 

     // read in the data 
     object[] importedObjects = engine.ReadString(@"""Date"",""Description"",""Original Description"",""Amount"",""Type"",""Category"",""Name"",""Labels"",""Notes"" 
""2/02/2012"",""ac"",""ac"",""515.00"",""a"",""b"","""",""javascript://"" 
""2/02/2012"",""test"",""test"",""40.00"",""a"",""d"",""c"","""","" """); 

     // check that 2 records were imported 
     Assert.AreEqual(2, importedObjects.Length); 

     // check the values for the first record 
     Format1 customer1 = (Format1)importedObjects[0]; 
     Assert.AreEqual(DateTime.Parse("2/02/2012"), customer1.Date); 
     Assert.AreEqual("ac", customer1.Description); 
     Assert.AreEqual("ac", customer1.OriginalDescription); 
     Assert.AreEqual(515.00, customer1.Amount); 
     Assert.AreEqual("a", customer1.Type); 
     Assert.AreEqual("b", customer1.Category); 
     Assert.AreEqual("", customer1.Name); 
     Assert.AreEqual("javascript://", customer1.Labels); 
     Assert.AreEqual("", customer1.Notes); 

     // check the values for the second record 
     Format1 customer2 = (Format1)importedObjects[1]; 
     Assert.AreEqual(DateTime.Parse("2/02/2012"), customer2.Date); 
     Assert.AreEqual("test", customer2.Description); 
     Assert.AreEqual("test", customer2.OriginalDescription); 
     Assert.AreEqual(40.00, customer2.Amount); 
     Assert.AreEqual("a", customer2.Type); 
     Assert.AreEqual("d", customer2.Category); 
     Assert.AreEqual("c", customer2.Name); 
     Assert.AreEqual("", customer2.Labels); 
     Assert.AreEqual(" ", customer2.Notes); 
    } 
} 

(참고의 첫 번째 라인 :)

심지어 따옴표 여기

[FieldQuoted('"', QuoteMode.OptionalForBoth)] 

와 선택 사항 여부를 지정할 수 있습니다 데이터와 함께 작동 콘솔 응용 프로그램입니다 데이터가 9 대신 8 개의 필드가있는 것 같습니다. 따라서 Notes 필드를 FieldOptional으로 표시했습니다.

0
string[] lines = new string[] 
{ 
    "\"Date\",\"Description\",\"Original Description\",\"Amount\",\"Type\",\"Category\",\"Name\",\"Labels\",\"Notes\"", 
    "\"2/02/2012\",\"ac\",\"ac\",\"515.00\",\"a\",\"b\",\"\",\"javascript://\"", 
    "\"2/02/2012\",\"test\",\"test\",\"40.00\",\"a\",\"d\",\"c\",\"\",\" \"", 
}; 

string[][] values = 
    lines.Select(line => 
     line.Trim('"') 
      .Split(new string[] { "\",\"" }, StringSplitOptions.None) 
      .ToArray() 
     ).ToArray(); 

lines 배열이 샘플에서 선을 나타냅니다 :여기 그것을하는 하나의 방법입니다. 각 " 문자는 C# 문자열 리터럴에서 \"으로 이스케이프되어야합니다.

각 줄마다 첫 번째 및 마지막 "자를 제거한 다음 "," 문자 시퀀스를 구분 기호로 사용하여 부분 문자열 모음으로 분할합니다.

" 문자가 자연스럽게 이스케이프 처리 된 경우에도 위의 코드는 이 작동하지 않음을 유의하십시오 (예 :).

편집 : 당신의 CSV는 스트림에서 읽을 수있는 경우, 수행하는 모든 필요는 다음과 같습니다

var lines = new List<string>(); 
using (var streamReader = new StreamReader(stream)) 
    while (!streamReader.EndOfStream) 
     lines.Add(streamReader.ReadLine()); 

위의 코드의 나머지 부분은 그대로 작동합니다.

편집 :이 같은 뭔가를 찾고 있는지 여부를 확인, 새로운 코드를 감안할 때 : 나는 같은 처지가

for (int i = 0; i < transactions.Length; ++i) 
{ 
    object oTrans = transactions[i]; 
    string sTrans = oTrans as string; 
    if (sTrans != null && 
     sTrans.StartsWith("\"") && 
     sTrans.EndsWith("\"")) 
    { 
     transactions[i] = sTrans.Substring(1, sTrans.Length - 2); 
    } 
} 
+0

내가 준 코드는 스트림에서 업로드되고 읽히는 .csv 파일의 예입니다. – chobo2

+0

그들은 일련의 객체를 반환하는 "engine"빌드 메소드를 가지고 있습니다. 변경 사항을 확인하십시오. – chobo2

0

내가 내 목록 객체에 값을로드 할 때 나는 따옴표를 교체 :

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Windows.Forms; 

namespace WindowsFormsApplication6 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      LoadCSV(); 
     } 

     private void LoadCSV() 
     { 
      List<string> Rows = new List<string>(); 
      string m_CSVFilePath = "<Path to CSV File>"; 

      using (StreamReader r = new StreamReader(m_CSVFilePath)) 
      { 
       string row; 

       while ((row = r.ReadLine()) != null) 
       { 
        Rows.Add(row.Replace("\"", "")); 
       } 

       foreach (var Row in Rows) 
       { 
        if (Row.Length > 0) 
        { 
         string[] RowValue = Row.Split(','); 

         //Do something with values here 
        } 
       } 
      } 
     } 

    } 
} 
+0

옵션을 살펴본 결과이 필드 속성이 트릭을 수행 할 수있는 것처럼 보입니다. FieldQuoted (QuoteMode.OptionalForBoth)입니다. 나는 그들이 하나의 옵션을 잃어 버렸다고 생각한다. (하나는 읽기와 쓰기 모두 따옴표를 무시할 것이다.) – chobo2

+0

@ chobo2 - 그래도 괜찮 으면 좋겠지 만, Filehelpers를 사용한다면 여전히 클라이언트 컴퓨터에 DLL을 설치해야한다. 내 솔루션은 추가 파일이 필요없는 Framework 만 사용합니다. –

0

내가 개발 도움이 될이 코드 :

using (StreamReader r = new StreamReader("C:\\Projects\\Mactive\\Audience\\DrawBalancing\\CSVFiles\\Analytix_ABC_HD.csv")) 
{ 
    string row; 

    int outCount; 
     StringBuilder line=new StringBuilder() ; 
     string token=""; 
     char chr; 
     string Eachline; 

    while ((row = r.ReadLine()) != null) 
    { 
     outCount = row.Length; 
     line = new StringBuilder(); 
     for (int innerCount = 0; innerCount <= outCount - 1; innerCount++) 
     {     
      chr=row[innerCount]; 

      if (chr != '"') 
      { 
       line.Append(row[innerCount].ToString()); 
      } 
      else if(chr=='"') 
      { 
       token = ""; 
       innerCount = innerCount + 1; 
       for (; innerCount < outCount - 1; innerCount++) 
       { 
        chr=row[innerCount]; 
        if(chr=='"') 
        { 
         break; 
        } 

        token = token + chr.ToString();        
       } 

       if(token.Contains(",")){token=token.Replace(",","");} 
       line.Append(token); 
      }     
     } 
     Eachline = line.ToString(); 
     Console.WriteLine(Eachline); 
    } 
}