I am currently writing a Powershell code to import a very large DataTable into an Excel-File without having Excel installed on that machine. All is fine till now, except that I dont know how to create the worksheet.xml structure via an XmlTextWriter.
This is the final XML structure that I need to create via XmlTextWriter:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" >
<sheetData/>
</worksheet>
This is the Powershell code that I have till now for that part:
# create the settings:
$settings = [System.Xml.XmlWriterSettings]::new()
$settings.Encoding = [System.Text.Encoding]::UTF8
$settings.Async = $true
# create the XML:
$sb = [System.Text.StringBuilder]::new()
$wr = [System.Xml.XmlTextWriter]::create($sb, $settings)
[void]$wr.WriteStartDocumentAsync($true)
[void]$wr.WriteStartElement("worksheet") #, "http://schemas.openxmlformats.org/spreadsheetml/2006/main")
[void]$wr.WriteStartAttribute("r", "xmlns", "http://schemas.openxmlformats.org/2006/relationships")
[void]$wr.WriteStartElementAsync($null, "sheetdata", $null)
[void]$wr.WriteEndElementAsync()
[void]$wr.WriteEndElementAsync()
$wr.Flush()
# show result:
$sb.ToString()
But the result is not the expected XML:
<?xml version="1.0" encoding="utf-16" standalone="yes"?><worksheet r:xmlns="" xmlns:r="http://schemas.openxmlformats.org/2006/relationships"><sheetdata /></worksheet>
- The encoding is still UTF-16 instead of UTF-8
- I am getting an extra "r:xmlns"-entry (?)
- I am not able to create the "xmlns"-entry PLUS the "xmlns:r"-entry for the same element
- not all calls are running/are available in Async-Mode.
Can someone please help?
This is the final code I came up with based on the input from wasmachien:
Here is the output: