VB.Net: Writing To Excel Workbook as Text

我只是一个虾纸丫 提交于 2019-12-12 06:22:40

问题


I have written the following 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

It runs as expected, but some values are written as "General" and others are written as "Date". This leads to values such as 07-2-3018 being turned into 7/2/3018. Then if I change that cell to "Text" or "General"(manually) it turns into "408525".

Is there a way to specify that I want it to be written as text to achieve 07-2-3-18 being written?


回答1:


When you put data that might be a string, or might be a date, Excel does wacky things with it, as you've observed, because it has no way of knowing whether the data you've provided should be one type or another.

Usually, anything that can be interpreted as a Date type, is interpreted as such. So, 1/1/2017 would be a valid date but 13/47/5047 cannot be, so Excel will treat the latter as a string literal, the former as a Date type. If a value is considered a Date, then it is also a Long numeric. The 408525 value is the long numeric representation of the Date value 7/2/3018.

There should be a NumberFormat property of your Cells object (which is an Excel.Range type), but the NumberFormat doesn't change the underlying value, and it's the interpretation of the value which is confusing Excel and causing it to represent date-like values as Dates.

You can always prepend the cell value with an apostrophe, which will force Excel to interpret as string, e.g.:

theSheet.Cells(rowNumber, 2) = "'" + myName.Descendants(myNameSpaces("ns") + "id").Value


来源:https://stackoverflow.com/questions/43720499/vb-net-writing-to-excel-workbook-as-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!