@CzarR , Welcome to Microsoft Q&A, you could try the following code to export the data from the "Query Data" node to an Excel file.
Please install the nuget-package Microsoft.Office.Interop.Excel first of all.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
static void Main(string[] args)
{
string path = "D:\\test.xml";
XDocument doc = XDocument.Load(path);
var result = doc.Descendants("QUERY_DATA");
List<string> collist = new List<string>();
foreach (var item in result)
{
var atts = item.Attributes();
foreach (var att in atts)
{
collist.Add(att.Name.ToString());
}
}
collist = collist.Distinct().ToList();
DataTable table = new DataTable();
foreach (var item in collist)
{
table.Columns.Add(item);
}
foreach (var item in result)
{
var arr = item.Attributes().Select(i => i.Value.ToString()).ToArray();
table.Rows.Add(arr);
}
string path1 = "D:\\test.xlsx";
ExportToExcel(table, path1);
}
public static void ExportToExcel(DataTable tbl, string excelFilePath = null)
{
try
{
if (tbl == null || tbl.Columns.Count == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
var excelApp = new Excel.Application();
excelApp.Workbooks.Add();
// single worksheet
Excel._Worksheet workSheet = excelApp.ActiveSheet;
// column headings
for (var i = 0; i < tbl.Columns.Count; i++)
{
workSheet.Cells[1, i + 1] = tbl.Columns[i].ColumnName;
}
// rows
for (var i = 0; i < tbl.Rows.Count; i++)
{
// to do: format datetime values before printing
for (var j = 0; j < tbl.Columns.Count; j++)
{
workSheet.Cells[i + 2, j + 1] = tbl.Rows[i][j];
}
}
// check file path
if (!string.IsNullOrEmpty(excelFilePath))
{
try
{
workSheet.SaveAs(excelFilePath);
excelApp.Quit();
Console.WriteLine("Excel file saved!");
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
+ ex.Message);
}
}
else
{ // no file path is given
excelApp.Visible = true;
}
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: \n" + ex.Message);
}
}
Note: I noticed that your xml has an error, Please modify it to the correct xml.(Missing ")
Change
<CWL_RESPONSE RequestType="Query" ClientID="XXX ResponseDateTime="11/3/2021 4:31:57 PM">
Into:
<CWL_RESPONSE RequestType="Query" ClientID="XXX" ResponseDateTime="11/3/2021 4:31:57 PM">
Result in excel file:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.