VB.Net:作为文本写入Excel工作簿
我写了以下function…
Public Function writeAUTLSheet(doc As XDocument, myNameSpaces As Dictionary(Of String, XNamespace), theSheet As Excel.Worksheet) 'Grab the number of the last row to not overwrite Dim rowNumber As Integer = getLastRow(theSheet) For Each myName As XElement In doc.Descendants.Elements(myNameSpaces("ns4") + "autl") theSheet.Cells(rowNumber, 1) = doc.Descendants.Elements(myNameSpaces("ns") + "number").Value theSheet.Cells(rowNumber, 2) = myName.Descendants(myNameSpaces("ns") + "id").Value theSheet.Cells(rowNumber, 3) = myName.Descendants(myNameSpaces("ns") + "name").Value rowNumber = rowNumber + 1 Next End Function
它按预期运行,但有些值写为“常规”,其他值写为“date”。 这导致诸如07-2-3018的值被变成7/2/3018。 然后,如果我将该单元格更改为“文本”或“常规”(手动)它变成“408525”。
有没有办法指定我希望它被写为文本来实现07-2-3-18被写入?
当你把可能是string的数据,或者可能是一个date的时候,如你所见,Excel做了一些古怪的事情,因为它无法知道你提供的数据应该是一种types还是另一种types。
通常,任何可以被解释为Date
types的东西都被解释为这样。 所以,1/1/ 1/1/2017
将是一个有效的date,但13/47/5047
不能,所以Excel将把后者视为一个string文字,前者作为Date
types。 如果一个值被认为是一个Date
,那么它也是一个Long
整数。 408525
值是Date
值7/2/3018
的长数字表示7/2/3018
。
应该有一个你的Cells
对象(这是一个Excel.Range
types)的NumberFormat
属性,但是NumberFormat
不会改变基础值 ,这是对令人困惑的Excel的值的解释,并导致它表示date样值作为date。
你总是可以用单引号括起单元格的值,这将强制Excel解释为string,例如:
theSheet.Cells(rowNumber, 2) = "'" + myName.Descendants(myNameSpaces("ns") + "id").Value