2009-12-11 11 views
1

도움이 될 것입니다! CSV로 Google 연락처를 가져오고 있습니다. 문제는 코드에서 언급 한 CSV 파일의 특정 헤더 값만 가져올 수 있다는 것입니다. 누구든지 Google CSV 파일을 가져 오는 동안 전체 세트를 가져올 소스 코드를 얻을 수 있습니까?.NET에서 CSV 파일 가져 오기

private void GoogleCsv() 
{ 
    StreamReader Sr = new StreamReader(Server.MapPath("CSVLoad//" + FileUpload.FileName)); 
    System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
    string s; 
    Int64 count = 0, flag = 0; 
    while (!Sr.EndOfStream) 
    { 
     s = Sr.ReadLine(); 

     a = s.Split(',')[0]; 
     b = s.Split(',')[1]; 
     c = s.Split(',')[2]; 
     d = s.Split(',')[3]; 
     e = s.Split(',')[4]; 

     if (count == 0) 
     { 
      if ((a == "Name") && (b == "E-mail 1 - Value") && (c == "Phone 1 - Value") && (d == "Address 1 - Formatted") && (e == "Organization 1 - Name")) 
      { 
       flag = flag + 1; 
       count = count + 1; 
      } 
      else 
      { 
       break; 
      } 
     } 
     else if (count > 0) 
     { 
      if (flag == 1) 
      { 
       Contact contact = new Contact(); 
       contact.ContactFirstName = a; 
       contact.ContactLastName = ""; 
       contact.ContactEmail = b; 
       contact.CompanyName = e; 
       contact.ContactPhone = ""; 
       contact.MobileNo = c; 
       contact.Designation = d; 
       contact.Streetone = ""; 
       contact.Streettwo = ""; 
       contact.Area = ""; 
       contact.Userid = Convert.ToInt64(Session["UserId"].ToString()); 
       contact.Organizationid = Convert.ToInt64(Session["OrgId"].ToString()); 
       contact.Stateid = 19; 
       contact.Countryid = 2; 
       contact.Createdby = 106; 
       contact.Industryid = 287; 
       contact.Accgroupid = 627; 
       _importController.CsvImportDetails(contact); 
      } 
     } 
    } 
    Sr.Close(); 
    File.Delete(Server.MapPath("CSVLoad//" + FileUpload.FileName)); 
} 

답변

3

나는 그것을, 무료로 빠르고 사용하기 쉬운,로드 CSV 데이터를이 CsvReader 클래스를 사용합니다.

+0

CsvReader 전체 CSV 파일을 읽을 것이다 포함 된 열. –

2

이런 식으로 항상 나는 FileHelpers으로 바뀌 었습니다. 왜 그 모든 저수준 측면을 이미 다루고있는 솔루션이있을 때 구분 기호와 모든 gnary 세부 정보로 휠을 재발행하고 투쟁해야합니까?

기본적으로 가져올 클래스 (기본적으로 필드 목록)를 정의하고 구분 기호 및 무시 필드 등을 정의한 다음 FileHelperEngine<T>.ReadFile()을 호출하고 완료하십시오.

강력 추천!

+0

나는 이것을 한두번 사용하도록 유혹되었는데, 여기에 좋은 권고가있다. –

0

흥미롭고 우아한 하나의 옵션은 LINQToCSV 프로젝트입니다.

+0

LINQToCSV 및 LumenWorks (http://www.codeproject.com/KB/database/CsvReader.aspx)를 테스트 한 후 두 번째 테스트를 결정했습니다. 사용하기 쉽고 정말 빠릅니다. – Oleiro

0
class DynamicCSV : DynamicObject 
{ 
private Dictionary<String, int> _fieldIndex; 
private string[] _RowValues; 
public DynamicCSV(string currentRow, Dictionary<string, int> fieldIndex) 
{ 
    _RowValues = currentRow.Split(','); 
    _fieldIndex = fieldIndex; 
} 


public YOURLINQOBject export() { 
    return new YOURLINQOBject() 
} 

public DynamicCSV(string[] values, Dictionary<string, int> fieldIndex) 
{ 
    _RowValues = values; 
    _fieldIndex = fieldIndex; 
    //var that = new DynamicObject(); 
    //that.TrySetMember(
} 



private string TransitionName(string inputFieldName) 
{ 
    return Repo.TransitionThisName(inputFieldName); 
} 

public override bool TryGetMember(GetMemberBinder binder, out Object result) 
{ 
    var fieldName = binder.Name.ToUpperInvariant(); 
    if (_fieldIndex.ContainsKey(fieldName)) 
    { 
     result = _RowValues[_fieldIndex[fieldName]]; 
     return true; 
    } 
    result = null; 
    return false; 
} 


public override bool TrySetMember(SetMemberBinder binder, object value) 
{ 
    var fieldName = binder.Name.ToUpperInvariant(); 
    if (_fieldIndex.ContainsKey(fieldName)) 
    { 
     _RowValues[_fieldIndex[fieldName]] = value.ToString(); 
     return true; 
    } 
    return false; 
} 

public override string ToString() 
{ 
    var sb = new StringBuilder(); 
    sb.AppendLine("*******************************************"); 
    foreach (var field in _fieldIndex) 
    { 
     sb.AppendLine(field.Key + " --- " + _RowValues[_fieldIndex[field.Key]]); 
    } 
    sb.AppendLine("*******************************************"); 
    return sb.ToString(); 
} 

}

이어서 함께

public class DynamicCSVEnum : IEnumerable 
{ 
    private PeopleEnumerator _peopleEnum; 
    public DynamicCSVEnum(string filename) 
    { 
     _peopleEnum = new PeopleEnumerator(filename); 
    } 
    IEnumerator IEnumerable.GetEnumerator() 
    { 
     // return a PeopleEnumerator 
     return _peopleEnum; 
    } 
} 


public class PeopleEnumerator : IEnumerator 
{ 
    //private List<MKG> theList; 
    //private int _currentIndex; 

    private Microsoft.VisualBasic.FileIO.TextFieldParser _FileStream; 
    private Dictionary<string, int> _FieldNames; 
    private DynamicCSV _CurrentRow; 
    private string _filename; 

    public PeopleEnumerator(string filename) 
    { 
     _filename = filename; 
     //theList = new List<MKG>(); 
     //theList.Add(new MKG() { Id = 0 }); 
     //theList.Add(new MKG() { Id = 1 }); 
     //theList.Add(new MKG() { Id = 2 }); 
     //_currentIndex = -1; 
     GetEnumerator(); 
    } 

    private void GetEnumerator() 
    { 
     _FileStream = new Microsoft.VisualBasic.FileIO.TextFieldParser(_filename); 
     _FileStream.Delimiters = new String[] { "," }; 
     _FileStream.HasFieldsEnclosedInQuotes = true; 
     _FileStream.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited; 
     var fields = _FileStream.ReadFields(); 
     _FieldNames = new Dictionary<string, int>(); 
     for (var i = 0; i <= fields.Length - 1; i++) 
     { 
      _FieldNames.Add(GetSafeFieldName(fields[i]), i); 
     } 
     _CurrentRow = new DynamicCSV(_FileStream.ReadFields(), _FieldNames); 
    } 
    public void Reset() 
    { 
     //_currentIndex = 0; 
     _FileStream.Close(); 
     GetEnumerator(); 
    } 

    public bool MoveNext() 
    { 
     //_currentIndex++; 
     //if (_currentIndex < theList.Count) 
     //{ 

     // return true; 
     //} 
     //return false; 
     var line = _FileStream.ReadFields(); 
     if (line != null && line.Length > 0) 
     { 
      _CurrentRow = new DynamicCSV(line, _FieldNames); 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 

    public object Current 
    { 
     //get 
     //{ 
     // return theList[_currentIndex]; 
     //} 
     //set 
     //{ 
     // theList[_currentIndex] = (MKG)value; 
     //} 
     get { return _CurrentRow; } 

    } 

    string GetSafeFieldName(string input) 
    { 
     return input.Replace(" ", "").Replace("_", "").Replace(".","").Replace("#","").Replace("/","").Replace("\\","").ToUpperInvariant(); 
    } 

} 

모든 행을로드하기 위해, 그때까지 걸리는 것은 모두 간단한

  var foo = new DynamicCSVEnum(savedFileName); 

      foreach (DynamicCSV item in foo) 
      { 
       retVal.Add(item.LinqObjectExport()); 
      } 

      foreach (var item in retVal) 
      { 
       item.ClientSet = dsid; 
      } 
      repo.InsertDataSet(retVal); 
+0

매우 감사합니다 !!!!!! – renisha

관련 문제