如何控制 JSON 文件如何显示其数据?

问题描述 投票:0回答:0

到目前为止,我可以读取 excel 电子表格并将其转换为 JSON,但我正在努力操作我想要从电子表格中获取的数据以及我希望它如何显示。

这就是我阅读表格并将其添加到列表中的方式

foreach (Row row in rows) 
            {
                Dictionary<string, object> rowValues = new Dictionary<string, object>();
                int columnNumer = 1;

                List<InterfaceRecord> interfaceRecords = new List<InterfaceRecord>();   


                foreach (Cell cell in row.Elements<Cell>())
                {
                  
                    string columnName = GetColumnName(columnNumer); 
                    string cellValue = GetCellValue(cell, spreadsheetDocument);


                    rowValues[columnName] = cellValue;

                    InterfaceRecord record = new InterfaceRecord();
                    decimal value = -1;
                    decimal.TryParse(GetCellValue(cell, spreadsheetDocument), out value);
                    record.Value = value;
                    record.SampleNumber = "";

                    interfaceRecords.Add(record);

                    columnNumer++;
                }
                data.Add(rowValues);
            }

这里是JSON的转换方式

            //convert to JSON
            string json = JsonConvert.SerializeObject(data, Formatting.Indented);
            string jsonPath = properties.Path;
            string randomFileName = DateTime.Today.Ticks.ToString();
            File.WriteAllText($"{jsonPath}\\RandomFilen.json", json);

将数字列索引映射到 Excel 中使用的相应的基于字母的列名。

public static string GetColumnName(int columnNumber)
        {
            int dividend = columnNumber;
            string columnName = string.Empty;
            int modulo;

            while (dividend > 0)
            {
                modulo = (dividend - 1) % 26;
                columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
                dividend = (int)((dividend - modulo) / 26);
            }

            return columnName;
        }

这是界面

class InterfaceRecord
    {
        public string? SampleNumber { get; set; }
        public decimal Value { get; set; }
        public DateTime CreatedAt { get; set; }
        public long ClientID { get; set; }
        public string? MachineName { get; set; }
    }

这里是 JSON 文件最初的样例

"A": "Sample Name",//this is the Sample Number
    "B": "Description",
    "C": "Saved or unsaved State",
    "D": "Spectrum quality check summary",
    "E": "SiO2"//This is the value

这就是我想要的显示方式

"Sample Number": "123-ABC",
    "Value": 0.1234,
    "CreatedAt",
    "Machine Name": "Analyzer A",//Not in spreadsheet, just how I want to categorize
    "ClientID":  123
c# json excel winforms openxml-sdk
© www.soinside.com 2019 - 2024. All rights reserved.