iop*_*iop 3 c# format excel clipboard cell
在C#中,我需要将数据网格行复制到excel.因为一行中的某些值是双精度数,所以" -Infinity"值是可能的.
我试图将行复制为DataFormats.UnicodeText或者DataFormats.Text但是这给了我输出" #NAME?"我应该看到的" -Infinity"(因为标准单元格格式,因为excel =在减号之前自动插入" " -Infinity).
当我Text在粘贴之前将单元格格式化为" "时,excel不会在" ="之前自动插入" -Infinity".顺便说一句,我不需要使用excel中的double值进行任何计算,因此文本格式对我来说没问题.
所以我的问题是如何将数据复制到剪贴板并将其粘贴到Excel中,同时将单元格格式设置为"text".
从Raw Clipboard查看器开始,您可以看到复制

到剪贴板导致Excel向剪贴板抛出大量不同的格式.

其中大部分都没有帮助,但其中一些是excel内部的,这意味着它(几乎)将保证数据与复制的数据相同.如果我是你,我可能会以XML SpreadSheet为目标,或者如果你感觉勇敢的Biff12也是xml(但是压缩).这将使您比普通文本更多地控制粘贴.
作为示例,上面的剪辑导致
<?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="s63">
<NumberFormat ss:Format="@"/>
</Style>
</Styles>
<Worksheet ss:Name="Sheet1">
<Table ss:ExpandedColumnCount="2" ss:ExpandedRowCount="2"
ss:DefaultRowHeight="15">
<Row>
<Cell><Data ss:Type="Number">1</Data></Cell>
<Cell><Data ss:Type="Number">2</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="String">Test</Data></Cell>
<Cell ss:StyleID="s63"><Data ss:Type="String" x:Ticked="1">-Infinity</Data></Cell>
</Row>
</Table>
</Worksheet>
</Workbook>
Run Code Online (Sandbox Code Playgroud)
所以看起来更深一点......当我试图用Clipboard.SetDataxml写入剪贴板
时,看起来.Net剪贴板类做了一些奇怪而不是那么美妙的事情
剪贴板以一堆箔条开始.这当然导致Excel拒绝剪贴板内容.
为了解决这个问题,我使用Windows API(user32)调用来处理剪贴板
[DllImport("user32.dll", SetLastError = true)]
static extern uint RegisterClipboardFormat(string lpszFormat);
[DllImport("user32.dll")]
static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem);
[DllImport("user32.dll", SetLastError = true)]
static extern bool CloseClipboard();
[DllImport("user32.dll", SetLastError = true)]
static extern bool OpenClipboard(IntPtr hWndNewOwner);
private static void XMLSpreadSheetToClipboard(String S)
{
var HGlob = Marshal.StringToHGlobalAnsi(S);
uint Format = RegisterClipboardFormat("XML SpreadSheet");
OpenClipboard(IntPtr.Zero);
SetClipboardData(Format, HGlob);
CloseClipboard();
Marshal.FreeHGlobal(HGlob);
}
Run Code Online (Sandbox Code Playgroud)