剪贴板.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²ˆû”
正如 BFree 的答案所示,SetText 和 TextDataFormat 可以作为解决方法
System.Windows.Forms.Clipboard.SetText(
"1\t2\t3\t4\n5\t6\t7\t8",
System.Windows.Forms.TextDataFormat.Text
);
我已经尝试过此操作并确认现在粘贴到 Excel 和 Word 中可以正常工作。在每种情况下,它都会粘贴为带有单元格而不是纯文本的表格。
仍然好奇为什么 CommaSeparatedValue 不工作。
.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);
使用制表符而不是逗号。即:
Clipboard.SetText("1\t2\t3\t4\t3\t2\t3\t4", TextDataFormat.Text);
我自己测试了一下,它对我有用。
我已成功使用(参见 BFree 的答案)作为列分隔符粘贴到 Excel 中,并且 作为行分隔符。
我最成功地解决了格式问题,方法是使用 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 错误处理和记录。