0

我正在从 excel 表中复制一个值 8.03,并使用下面的代码从剪贴板中读取 C# 中的值。出来的值是 8.0299999999999994 而不是 8.03。当我查看下面的 xml 时,值为 8.0299999999999994。xlsx 的 zip 文件中的 sheet1.xml 的值也为 8.02999999999999994。但是当我将值复制到记事本时,值会在 8.03 处被复制。我该怎么做才能像记事本一样将值复制为 8.03?

DataObject retrievedData =  Clipboard.GetDataObject() as DataObject;
    if (retrievedData.GetDataPresent("XML Spreadsheet"))
    {
        var sourceDataReader = new XmlTextReader(retrievedData.GetData("XML Spreadsheet") as System.IO.Stream);
         var doc = XDocument.Load(reader);
         var excelWorksheeet = doc.Element("Worksheet");
         XNamespace ns = "urn:schemas-microsoft-com:office:spreadsheet";
         XName worksheetName = ns + "Worksheet";
         var worksheetElement = doc.Root.Element(worksheetName);
    }

worksheetElement 具有以下值:

 <Worksheet ss:Name="Sheet1" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns="urn:schemas-microsoft-com:office:spreadsheet">
   <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" ss:DefaultRowHeight="15">
     <Row>
       <Cell>
         <Data ss:Type="Number">8.0299999999999994</Data> 
       </Cell>
      </Row>
    </Table>
  </Worksheet>
4

1 回答 1

1

The clipboard has support for several formats. Obviously the XML Spreadsheet format does a different rounding of the underlying float value than excel does. If you want to get the data exactly as notepad does, try to get the text representation instead.

Of course, copying as text will not get all the detailed information that XML Spreadsheet gives you, but it all depends on what you want to do with the data.

An alternative is to get both representations. Get the XML Spreadsheet format to get the detailed data and use the text format to get a display string.

于 2012-04-24T19:34:11.583 回答