Creating Excel Macro for Exporting XML to a certain folder

别来无恙 提交于 2019-11-30 20:49:16

问题


I need to create a macro (which I have never done before) and if you guys can guide me to a right path, it would be really appreciated.

What I'm doing currently: I have created a mapping XML which I have imported into Excel. Once it is imported into Excel, users will then go ahead and paste some data in it and export it to receive an XML data file, which then user can drop it to a FTP where the job picks it up and imports it into database.

Here's the problem: The export has following node, which I do not want:

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

Instead I want to replace it with following:

<?xml version="1.0" ?>
<Root xmlns="http://tempuri.org/CourseImport.xsd">

How do I automate this? Is there some kind of setting in Excel that could make it happen?

Basically, I want the export to have my root instead of the default root and I want to automatically be able to drop the file to specified path: example: \development\school\course import

Thanks!


回答1:


My co-worker actually helped me out with this. I thought I should share what I did

Sub ExportXML()
'
' Export XML Macro exports the data that is in Excel to XML.
'
Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")

'
newFileName = Application.GetSaveAsFilename("out.xml", "XML Files (*.xml), *.xmls")
If newFileName = False Then
Exit Sub
End If
If objFSO.FileExists(newFileName) Then
objFSO.DeleteFile (newFileName)
End If
ActiveWorkbook.XmlMaps("Root_Map").Export URL:=newFileName


Set objFile = objFSO.OpenTextFile(newFileName, ForReading)


Dim count
count = 0
Do Until objFile.AtEndOfStream
 strLine = objFile.ReadLine
 If count = 0 Then
    strNewContents = strNewContents & "<?xml version=""1.0"" ?>" & vbCrLf
ElseIf count = 1 Then
    strNewContents = strNewContents & "<Root xmlns=""http://tempuri.org/import.xsd"">" & vbCrLf
Else
    strNewContents = strNewContents & strLine & vbCrLf
End If
count = count + 1

Loop

objFile.Close

Set objFile = objFSO.OpenTextFile(newFileName, ForWriting)
 objFile.Write strNewContents

objFile.Close
End Sub


来源:https://stackoverflow.com/questions/15142523/creating-excel-macro-for-exporting-xml-to-a-certain-folder

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