2016-11-02 56 views
0

我試圖將數據表的內容發送到帶有標題的csv文件。有一個重複的問題,但接受的答案似乎只是工作的一半。在這一點上,我已經混合和匹配upvoted的答案,沒有運氣,需要在正確的方向點。將數據表的內容發送到帶有標題的csv文件

我可以將列寫入文件就好了,我可以很好地寫入數據但不能在一起。此外,數據永遠不會被引用,只有逗號不加引號。

//This is how the FileHelpers class is built 
public class ScannedFileInfo 
{ 
    //this prefix will handle the double quotes issue 
    //delimiters must reside between double quotes 
    //Must specify FieldOrder too 
    [FieldQuoted('"', QuoteMode.AlwaysQuoted)] 
    [FieldOrder(1)] 
    public string DA_Id; 
    [FieldQuoted('"', QuoteMode.AlwaysQuoted)] 
    [FieldOrder(2)] 
    public string Name; 
    [FieldQuoted('"', QuoteMode.AlwaysQuoted)] 
    [FieldOrder(3)] 
    public string Extension; 
    [FieldQuoted('"', QuoteMode.AlwaysQuoted)] 
    [FieldOrder(4)] 
    public string Fullname; 
    [FieldQuoted('"', QuoteMode.AlwaysQuoted)] 
    [FieldOrder(5)] 
    public string PathLength; 
    [FieldQuoted('"', QuoteMode.OptionalForBoth)] 
    [FieldOrder(6)] 
    public string Directory; 
} 

//this is how I send it to the file 
public static void ImportDirectory(string result, SqlConnection myconn, SqlConnection destConn ,ListBox lbInfo, DataGridView dgView) 
{ 
    //create data table code here - works fine... 
    MessageBox.Show("Scan complete. Starting Import..."); 

    //build file 
    var engine = new FileHelperEngine<ScannedFileInfo>(); 
    var orders = new List<ScannedFileInfo>(); 
    engine.HeaderText = engine.GetFileHeader(); 
    engine.WriteFile(@"C:\DirectoryScan.csv", orders); 
    MessageBox.Show("You now have proper labeled columns in your file."); 

    //now the data import is successful but it overwrites the column info 
    CommonEngine.DataTableToCsv(dt, @"C:\DirectoryScan.csv", ','); 
    MessageBox.Show("You now have data in your file, but no columns"); 

} 

回答

0

我不能推薦你看看CSVHelper夠了。這Nuget包已經救了我很多場合拉我的頭髮,我無法計數所有。

如果你到使用它,您可以使用配置設置來快速設置一個頭記錄,分隔符,忽略報價與否等

1

CommonEngine.DataTableToCsv()電話不支持所有的FileHelpersEngine特徵。特別是,字段引用和列標題丟失。 CommonEngine不像FileHelpersEngine<T>那樣全功能。而不是數據表,然後使用FileHelpersEngine<ScannedFileInfo>.WriteFile()

//create list of ScannedFileInfo here 
var records = new List<ScannedFileInfo>(); 
records.Add(new ScannedFileInfo() { Name = ..., etc... }); 
// (or if you prefer, loop through your datatable to build the list) 

MessageBox.Show("Scan complete. Starting Import..."); 

// build file 
var engine = new FileHelperEngine<ScannedFileInfo>(); 
engine.HeaderText = engine.GetFileHeader(); 
engine.WriteFile(@"C:\DirectoryScan.csv", records); 

MessageBox.Show("You now have data and properly labelled columns in your file."); 
相關問題