2014-06-09 47 views
3

在C#中,我使用下面的代碼將數據從一個WPF DataGrid複製到剪貼板,然後從剪貼板到CSV:在C#中,可以強制Clipboard.GetData輸出每個CSV值的引號嗎?

var originalSelectionMode = dataGrid.SelectionMode; 
dataGrid.SelectionMode = DataGridSelectionMode.Extended; 
dataGrid.SelectAllCells(); 
dataGrid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader; 
ApplicationCommands.Copy.Execute(null, dataGrid); 
dataGrid.UnselectAllCells(); 

// this is the line that's not working quite right: 
var text = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue); 

Clipboard.Clear(); 
dataGrid.SelectionMode = originalSelectionMode; 

File.WriteAllText(fullPathToFile, text); 

此代碼在大多數情況下,但有當問題您在其中一個單元格中有多行文本。比方說,你有這樣的網格數據:

A  |B  |C 
------------------- 
A1 |B1 |C1a,C2b 
------------------- 
A2 |B2 |C2a 
     |  |C2b 
------------------- 

Clipboard.GetData功能似乎只插入周圍的情況下的單元格的內容,你必須在你的內容逗號或雙引號字符雙引號,但如果你在那裏有一個換行符,因此,與上述電網的輸出應該是這樣的沒有做,它會自動:

A,B,C 
A1,B1,"C1a,C1b" 
A2,B2,C2a 
C2b 

注意,它並把周圍小區C1引號,但不是細胞C2。

有沒有一種方法可以讓Clipboard.GetData總是在每個單元格周圍加引號?如果不是,我該如何解決這個問題?

+2

沒有,但沒有什麼可以從做阻止你,你得到的數據出來之後。此外,無論.NET代碼將數據放在哪裏,都會添加這些引號......它不是內置於「剪貼板」類中的內容。 – Sheridan

+0

@Sheridan - 添加缺少的引號並不是一個小問題。 –

+1

@Sheridan,引號通過[DataGridClipboardHelper.FormatPlainCell](http://referencesource.microsoft.com/PresentationFramework/R/68eaf75082b68e8f.html)方法放入CSV中。確實它不是* Clipboard *類的一部分,但它是WPF DataGrid實現(及其輔助類)的一部分。 – elgonzo

回答

1

最簡單的方法是使用數據綁定並將字符串寫入csv。我創建了可綁定到數據網格中的示例類和允許新行創建/編輯(你可以在這個類別中,如果REQD補充通知):

public class Data 
{ 
    public Data() 
    { 
    } 

    public Data(string col1, string col2, string col3) 
    { 
     Col1 = col1; 
     Col2 = col2; 
     Col3 = col3; 
    } 

    public string Col1 { get; set; } 
    public string Col2 { get; set; } 
    public string Col3 { get; set; } 
} 

現在我重寫DataGrid的複製命令來控制定製複印:

this.DataGrid.CommandBindings.Add(new CommandBinding(ApplicationCommands.Copy, 
      new ExecutedRoutedEventHandler(CopyClicked))); 

在CopyClicked,我們創建一個使用數據視圖模型綁定類數據:

private void CopyClicked(object sender, ExecutedRoutedEventArgs e) 
    { 
     var stringBuilder = new StringBuilder(); 
     IList l = this.DataGrid.SelectedItems; 
     foreach (Data data in l) 
     { 
      stringBuilder.Append("\"" + data.Col1 +"\","); 
      stringBuilder.Append("\"" + data.Col2 + "\","); 
      stringBuilder.Append("\"" + data.Col3 + "\""); 
      stringBuilder.AppendLine(); 
     } 
     //Write to a file or straight to clipboard etc 
     Debug.WriteLine(stringBuilder.ToString()); 
    } 
+0

最終,我寫了自己的「CSV」實現,其中包含一些額外的功能,可以讓Excel從「有幫助」的方式保持行爲,例如「01-01」轉換爲「Jan-01」。 –

相關問題