如何使用 C# 将 CSV 数据粘贴到 Windows 剪贴板

问题描述 投票:0回答:5

我想要实现的目标

  • 我的应用程序生成一些表格数据
  • 我希望用户能够启动 Excel 并单击“粘贴”将数据作为 Excel 中的单元格放置
  • Windows 接受一种名为“CommaSeparatedValue”的格式,该格式与其 API 一起使用,因此这似乎是可能的
  • 将原始文本放在剪贴板上可以,但尝试使用此格式则不行
  • 注意:我可以从剪贴板正确检索 CSV 数据,我的问题是将 CSV 数据粘贴到剪贴板。

我尝试过的方法不起作用

剪贴板.SetText()

System.Windows.Forms.Clipboard.SetText(  
  "1,2,3,4\n5,6,7,8", 
  System.Windows.Forms.TextDataFormat.CommaSeparatedValue
  );

剪贴板.SetData()

System.Windows.Forms.Clipboard.SetData(
  System.Windows.Forms.DataFormats.CommaSeparatedValue,
  "1,2,3,4\n5,6,7,8", 
  );

在这两种情况下,某些内容都会被放置在剪贴板上,但是当粘贴到 Excel 中时,它会显示为一个垃圾文本单元格:“–§žý;pCyVk²ˆû”

更新 1:使用 SetText() 的解决方法

正如 BFree 的答案所示,SetTextTextDataFormat 可以作为解决方法

System.Windows.Forms.Clipboard.SetText(  
  "1\t2\t3\t4\n5\t6\t7\t8", 
  System.Windows.Forms.TextDataFormat.Text
  );

我已经尝试过此操作并确认现在粘贴到 Excel 和 Word 中可以正常工作。在每种情况下,它都会粘贴为带有单元格而不是纯文本的表格。

仍然好奇为什么 CommaSeparatedValue 工作。

c# windows csv clipboard paste
5个回答
43
投票

.NET Framework 将

DataFormats.CommaSeparatedValue
作为 Unicode 文本放置在剪贴板上。但正如http://www.syncfusion.com/faq/windowsforms/faq_c98c.aspx#q899q中提到的,Excel期望CSV数据是UTF-8内存流(很难说.NET或Excel是否是UTF-8内存流)不兼容的错误)。

我在自己的应用程序中提出的解决方案是将两个版本的表格数据同时作为制表符分隔文本和 CSV 内存流放置在剪贴板上。这允许目标应用程序以其首选格式获取数据。记事本和 Excel 更喜欢制表符分隔的文本,但您可以强制 Excel 通过“选择性粘贴...”命令抓取 CSV 数据以进行测试。

这里是一些示例代码(请注意,此处使用了 WPF 命名空间中的 WinForms 等效项):

// Generate both tab-delimited and CSV strings.
string tabbedText = //...
string csvText = //...

// Create the container object that will hold both versions of the data.
var dataObject = new System.Windows.DataObject();

// Add tab-delimited text to the container object as is.
dataObject.SetText(tabbedText);

// Convert the CSV text to a UTF-8 byte stream before adding it to the container object.
var bytes = System.Text.Encoding.UTF8.GetBytes(csvText);
var stream = new System.IO.MemoryStream(bytes);
dataObject.SetData(System.Windows.DataFormats.CommaSeparatedValue, stream);

// Copy the container object to the clipboard.
System.Windows.Clipboard.SetDataObject(dataObject, true);

7
投票

使用制表符而不是逗号。即:

Clipboard.SetText("1\t2\t3\t4\t3\t2\t3\t4", TextDataFormat.Text);

我自己测试了一下,它对我有用。


4
投票

我已成功使用(参见 BFree 的答案)作为列分隔符粘贴到 Excel 中,并且 作为行分隔符。


0
投票

我最成功地解决了格式问题,方法是使用 CSV 库 (KBCsv) 将数据写入临时文件夹中的 CSV 文件,然后使用

Process.Start()
在 Excel 中打开它。一旦进入 Excel,格式化就很容易(呃),从那里复制粘贴。

string filePath = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv";

using (var streamWriter = new StreamWriter(filePath))
using (CsvWriter csvWriter = new CsvWriter(streamWriter))
{
    // optional header
    csvWriter.WriteRecord(new List<string>(){"Heading1", "Heading2", "YouGetTheIdea" });

    csvWriter.ValueSeparator = ',';
    foreach (var thing in YourListOfThings ?? new List<OfThings>())
    {
        if (thing != null)
        {
            List<string> csvLine = new List<string>
                                         {
                                             thing.Property1, thing.Property2, thing.YouGetTheIdea
                                         };

            csvWriter.WriteRecord(csvLine);
        }
    }
}

Process.Start(filePath);

BYO 错误处理和记录。


0
投票

另一种解决方法使用 “Html 格式” 编写 html 并用 特殊标题

括起来

© www.soinside.com 2019 - 2024. All rights reserved.