简体   繁体   English

使用 C# 读取 Excel 单元格值并反序列化

[英]Read Excel cell value and de-serialize using C#

I have an Excel sheet in which I have values which are similar to this:我有一个 Excel 工作表,其中包含与此类似的值:

<Element id="1" Name="Some Name" Value="4" Unit="Some UNit" />

Now from my C# code, I'm reading this Excel.现在从我的 C# 代码中,我正在阅读这个 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.现在我的要求是反序列化单元格值并形成一个 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.我想在循环中添加它,但我不知道如何反序列化这个单元格值,因为它不完全是 XML 格式。 The only crude way I could think of is split based on spaces and access the values.我能想到的唯一粗略的方法是基于空格分割并访问值。

Is a better solution available?有更好的解决方案吗?

Note笔记

I was not clear before, but I what I meant was each cell in my Excel has this similar type of data.我之前不清楚,但我的意思是我的 Excel 中的每个单元格都有这种相似类型的数据。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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