使用
System.IO.MemoryStream
将字符串添加到剪贴板,而不在字符串值的开头和结尾添加额外的字节。
例如,以下字符串表示Microsoft Excel电子表格的一个片段:
class Program
{
[STAThread]
static void Main(string[] args)
{
string content = @"<?xml version=""1.0""?>
<?mso-application progid=""Excel.Sheet""?>
<Workbook xmlns=""urn:schemas-microsoft-com:office:spreadsheet""
xmlns:o=""urn:schemas-microsoft-com:office:office""
xmlns:x=""urn:schemas-microsoft-com:office:excel""
xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet""
xmlns:html=""http://www.w3.org/TR/REC-html40"">
<Styles>
<Style ss:ID=""Default"" ss:Name=""Normal"">
<Alignment ss:Vertical=""Bottom""/>
<Borders/>
<Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""/>
<Interior/>
<NumberFormat/>
<Protection/>
</Style>
<Style ss:ID=""s18"" ss:Name=""Currency"">
<NumberFormat
ss:Format=""_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)""/>
</Style>
<Style ss:ID=""s64"">
<Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""
ss:Bold=""1""/>
</Style>
<Style ss:ID=""s65"" ss:Parent=""s18"">
<Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""/>
</Style>
</Styles>
<Worksheet ss:Name=""Sheet1"">
<Table ss:ExpandedColumnCount=""2"" ss:ExpandedRowCount=""2""
ss:DefaultRowHeight=""15"">
<Row>
<Cell><Data ss:Type=""String"">Month</Data></Cell>
<Cell><Data ss:Type=""String"">Year</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID=""s64""><Data ss:Type=""String"">August</Data></Cell>
<Cell ss:StyleID=""s65""><Data ss:Type=""Number"">999.99</Data></Cell>
</Row>
</Table>
</Worksheet>
</Workbook>";
把它传给
Clipboard
类作为字符串:
Clipboard.SetData("XML Spreadsheet", content);
但是,将其序列化为字节,然后将其作为
内存流
Clipboard.SetData("XML Spreadsheet", new MemoryStream(Encoding.UTF8.GetBytes(content)));
创建与Excel兼容的剪贴板内容: