使用VBA导出到XML - 标头损坏

时间:2017-03-14 11:19:47

标签: xml excel vba excel-vba

我承认我正在做的事情可能是一个小工作,并且可能有更多技术上更好的方法来做到这一点,我没有想到。

我有一个excel表,通过粗野的方法创建XML结构。

基本上,A列下的单元格是(作为文本):

<?xml version="1.0" encoding="UTF-8" ?>
<ReportingInfo Version="1.0" CreationDate="2017-03-14T11:02:49">
<RecordInfo>
<FilingType>INIT</FilingType>
</RecordInfo>

然后我有一些vba代码将表格导出为xml文件:

Public Sub ExportToXML2()

Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Dim i As String
i = Date
i = Replace(i, "/", "")

Set shtToExport = ThisWorkbook.Worksheets("Output")     'Sheet to export as XML
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count) Application.DisplayAlerts = False
wbkExport.SaveAs Filename:="C:\Projects\XML_Report_" & i & ".xml", FileFormat:=xlCSV
Application.DisplayAlerts = True

wbkExport.Close SaveChanges:=False


Workbooks.Open "C:\Projects\XML_Report_" & i & ".xml"

End Sub

创建一个如下所示的XML文件:

"<?xml version=""1.0"" encoding=""UTF-8"" ?>"
"<ReportingInfo State=""GB"" Version=""1.0"" CreationDate=""2017-03-14T11:02:49"">"
<RecordInfo>
<FilingType>INIT</FilingType>
</RecordInfo>

为什么要显示额外的引号?

非常感谢。

1 个答案:

答案 0 :(得分:0)

当您另存为CSV或文本时,Excel将解析文本并用引号括起包含引号的任何内容。这是你的问题。为避免这种情况,请通过保存为文本流(最好是unicode)来创建XML,如此处所示。

输出中的数据,a1:a6:

<?xml version="1.0" encoding="UTF-8" ?>
<ReportingInfo Version="1.0" CreationDate="2017-03-14T11:02:49">
<RecordInfo>
<FilingType>INIT</FilingType>
</RecordInfo>
</ReportingInfo>

代码:

Public Sub ExportToXML2()
    Dim fso As Object, txt As Object
    Dim lines As Long
    Dim i As String

    i = Date
    i = Replace(i, "/", "")

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set txt = fso.CreateTextFile("C:\Projects\XML_Report_" & i & ".xml", True)
    With ThisWorkbook.Worksheets("Output") 'Sheet to export as XML
        For lines = 1 To .UsedRange.Rows.Count
            txt.WriteLine (.Cells(lines, 1))
        Next
    End With
    txt.Close
    Workbooks.Open "C:\Projects\XML_Report_" & i & ".xml"
End Sub

结果:

<?xml version="1.0" encoding="UTF-8" ?>
<ReportingInfo Version="1.0" CreationDate="2017-03-14T11:02:49">
<RecordInfo>
<FilingType>INIT</FilingType>
</RecordInfo>
</ReportingInfo>

在Excel中打开xml:

/ReportingInfo      
/@CreationDate  /@Version   /RecordInfo/FilingType
14/03/17 11:02  1   INIT