I have an Excel sheet in which I have values which are similar to this:
<Element id="1" Name="Some Name" Value="4" Unit="Some UNit" />
Now from my C# code, I'm reading this Excel.
I have a class file in my application similar to
public class InputData{
[DataMember(Name = "id")]
public string id { get; set; }
[DataMember(Name = "Name")]
public string Name { get; set; }
[DataMember(Name = "Value")]
public string Value { get; set; }
[DataMember(Name = "Unit")]
public string Unit { get; set; }
}
I'm able to read the cell value using following code :
foreach (var worksheet in Workbook.Worksheets(@"C:\Test\Book1.xlsx"))
{
foreach (var row in worksheet.Rows)
{
foreach (var cell in row.Cells)
{
Console.WriteLine(cell.Text);
}
}
}
I have followed this link to do so.
Now my requirement is to deserialize the cell value and form a list of InputData.
List<InputData> lst = new List<InputData>();
InputData inputData = new InputData;
inputData.id ="" ; //assign value
inputData.Name ="" ; //assign value
inputData.Value ="" ; //assign value
inputData.Unit ="" ; //assign value
lst.Add(inputData);
I want to add this in the loop, but I do not know how to deserialize this cell value as it is not exactly XML format. The only crude way I could think of is split based on spaces and access the values.
Is a better solution available?
I was not clear before, but I what I meant was each cell in my Excel has this similar type of data. I'm trying to loop through each cell and make a list.
EDIT
foreach (var row in worksheet.Rows)
{
foreach (var cell in row.Cells)
{
Console.WriteLine(cell.Text);
Console.WriteLine(XDocument.Parse(cell.Text).Root.Attribute("id").Value);
Console.ReadLine();
}
}
In the first line , it prints this as mentioned above.
<Element id="1" Name="Some Name" Value="4" Unit="Some UNit" />
您可以使用XDocument.Parse
,例如:
inputData.id = XDocument.Parse(cell.Text).Root.Attribute("id").Value
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.