到目前为止,我可以阅读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);
将数字列索引Map到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
2条答案
按热度按时间xv8emn3q1#
只需将列名添加为JsonProperty
或者,如果要使用新属性名再次序列化JsonConstructor,请添加它
hc2pp10m2#
如果我没理解错的话,您要查找的是JSON属性。
将串行化为
链接:
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/customize-properties?pivots=dotnet-7-0