2014-03-28 80 views
0

我有一個巨大的csv文件,我想上傳到db2表中。唯一的問題是,它削減了列,所以我甚至沒有一半的列到數據表中。我知道我可以手動添加列,但沒有辦法以另一種方式做到這一點?datatable削減列大小

static DataTable GetDataTableFromCsv(string path, string csvSelection, bool isFirstRowHeader) 
    { 
     string header = isFirstRowHeader ? "Yes" : "No"; 


     string pathOnly = Path.GetDirectoryName(path); 
     string fileName = Path.GetFileName(path); 
     //string sql = @"SELECT " + csvSelection + " FROM [" + fileName + "];"; 
     string sql = @"SELECT * FROM [" + fileName + "];"; 

     using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";Extended Properties=\"Text;HDR=" + header + "\"")) 
     using (OleDbCommand command = new OleDbCommand(sql, connection)) 
     using (OleDbDataAdapter adapter = new OleDbDataAdapter(command)) 
     { 
      DataTable dataTable = new DataTable(); 
      dataTable.Locale = CultureInfo.CurrentCulture; 

      adapter.Fill(dataTable); 
      writeSchema(dataTable.Columns[0].ToString(), pathOnly, fileName); 
      return dataTable; 
     } 

    } 

回答

0

我不得不加列 「人工」

private static List<string> getHeader(string fileName) 
       { 
        string fullpath = @ImportPath + "\\" + fileName; 
        List<string> header = new List<string>(); 
        var reader = new StreamReader(File.OpenRead(fullpath)); 

        while (!reader.EndOfStream) 
        { 
         var line = reader.ReadLine(); 
         var values = line.Split(';'); 

         foreach (var spalte in values) 
         { 
          header.Add(spalte); 
         } 
         reader.Close(); 
         return header; 
        } 
        return null; 
       } 

    static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader, string csvSelection) 
      { 
       string header= isFirstRowHeader ? "Yes" : "No"; 

       string pathOnly = Path.GetDirectoryName(path); 
       string fileName = Path.GetFileName(path); 
       List<string> headerList = getHeader(fileName); 
       string sql = @"SELECT " + "*" + " FROM [" + fileName + "]"; 
       //string sql = @"SELECT * FROM [" + fileName + "];"; 

       using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";Extended Properties=\"Text;HDR=" + headerList + ";FMT=Delimited(;)\"")) 
       using (OleDbCommand command = new OleDbCommand(sql, connection)) 
       using (OleDbDataAdapter adapter = new OleDbDataAdapter(command)) 
       { 
        DataTable dataTable = new DataTable(); 
        dataTable.Locale = CultureInfo.CurrentCulture; 
        foreach (var item in headerList) 
        { 
         dataTable.Columns.Add(item); 
        } 

        adapter.Fill(dataTable); 
        writeSchema(dataTable.Columns, pathOnly, fileName); 
        return dataTable; 
       } 

      }