简体   繁体   中英

How to serialize Xml (from XLSX files) to Json ? C# .NET Json.Net

I'm processing different kind of Xlsx files.
These files have multiples possibility of column eg 2 or 6 or even 7 Columns)
I read the Xml data inside using OpenXml and i would like to generate Json files from each worksheet.
Actually i'm able to read and to iterate through every worksheet but it seems weird when i try to convert it into Json format using Newtonsoft.Json


The Excel files is similare to this
Item 1 || Item 2 || Item 3
V1 || V2 || V3
V1 || V2 || V3
V1 || V2 || V3

But the generated JSON file is similare to this
[
[Item 1 ,Item 2 ,Item 3]
[V1 ,V2 ,V3]
[V1 ,V2 ,V3]
[V1 ,V2 ,V3]
]


And i would like to format it like this


{
{"Item 1":"V1" ,"Item 2":"V2" ,"Item 3":"V3"}
{"Item 1":"V1" ,"Item 2":"V2" ,"Item 3":"V3"}
{"Item 1":"V1" ,"Item 2":"V2" ,"Item 3":"V3"}
}

Here is my code :

using (SpreadsheetDocument excelDocument = SpreadsheetDocument.Open(file, false)) { var documentBody = excelDocument.WorkbookPart.Workbook;

            var sheets = documentBody.Sheets.Cast<Sheet>().ToList();
            sheets.ForEach(x => Console.WriteLine(String.Format("RelationshipId:{0}\n SheetName:{1}\n SheetId:{2}", x.Id.Value, x.Name.Value, x.SheetId.Value)));

            SharedStringTablePart sstpart = excelDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
            SharedStringTable sst = sstpart.SharedStringTable;

            Console.WriteLine("Worksheet count = {0}", documentBody.WorkbookPart.WorksheetParts.Count());

            foreach (var worksheetPart in documentBody.WorkbookPart.WorksheetParts)
            {

                DocumentFormat.OpenXml.Spreadsheet.Worksheet sheet = worksheetPart.Worksheet;

                var cells = sheet.Descendants<Cell>();
                var rows = sheet.Descendants<Row>();

                Console.WriteLine("Row count = {0}", rows.LongCount());
                Console.WriteLine("Cell count = {0}", cells.LongCount());
                var list = new List<string[]>();
                foreach (Row row in rows)
                {
                    Console.WriteLine("Row number: {0}", row.RowIndex);
                    list.Add(row.Elements<Cell>().Select(x => x.InnerText).ToArray());
                    foreach (Cell c in row.Elements<Cell>())
                    {
                        if (c.CellValue != null)
                        {
                            Console.WriteLine("Cell contents: {0}", c.CellValue.Text);

                        }
                    }
                }
                var i = JsonConvert.SerializeObject(list, Newtonsoft.Json.Formatting.Indented);


            }
        }

In your case I recommend to use List of ExpandoObject instead of List of string[]. It's a dynamic object generated as a IDictionnary

var list = new List<ExpandoObject>();
var expandoObject = new ExpandoObject();
var dict = (IDictionary<string, Object>)expandoObject;
dict.Add("NewProp", "prop value");
dict.Add("SecondProp", 58);
list.add(expandoObject);

To convert an XML node contained in string xml into a JSON string

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

To convert JSON text contained in string json into an XML node

 XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

Documentation here: Click Here for Documentation

OR Try this below Code there i have used dictionary

class Program
{
static void Main()
{
    var xml = 
    @"<Columns>
      <Column Name=""key1"" DataType=""Boolean"">True</Column>
      <Column Name=""key2"" DataType=""String"">Hello World</Column>
      <Column Name=""key3"" DataType=""Integer"">999</Column>
    </Columns>";
    var dic = XDocument
        .Parse(xml)
        .Descendants("Column")
        .ToDictionary(
            c => c.Attribute("Name").Value, 
            c => c.Value
        );
    var json = new JavaScriptSerializer().Serialize(dic);
    Console.WriteLine(json);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM