2016-11-02 34 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."); 
相关问题