Получение значения поля через рефлексию с типом поля

Имеется код, который должен вытащить данные из атрибута(имя поля на кириллице и месторасположение на листе в Excel), а потом записать имя поля и его значение в ячейку в Excel'е. Делаю я всё это через рефлексию. Вопрос такой: как вытащить значение поля с типом данных поля или как узнать тип данных поля, а потом скастить? Когда я вытаскиваю значение поля, то вытаскивается object, который я могу безопасно скастить только в строку. Отсюда получается, что данные в Excel'e все в строковом виде, а там есть формулы, даты и т.д

Основной код, который вытаскивает через рефлексию и генерирует строки в таблице:

var requestTransportationRatesFob = new RequestTransportationRate();

using (AppDbContext db = new AppDbContext())
{
    requestTransportationRatesFob = db.RequestTransportationRates
        .Include(x => x.ResponseTransportationRequests)
        .FirstOrDefault(x => x.Id == Guid.Parse("052076ed-5a1d-4ee8-8e89-6dc60d6dba8f"));
}

if(requestTransportationRatesFob != null && requestTransportationRatesFob.CargoPickupAddress == null)
{
    var wb = new XLWorkbook();
    var reportFbo = wb.Worksheets.Add("FBO");
    int numberOfColumnIterator = 0;

    foreach (PropertyInfo prop in requestTransportationRatesFob.GetType().GetProperties())
    {
        object[] attrs = prop.GetCustomAttributes(true);

        foreach (object attr in attrs)
        {
            LocationAttribute attrName = attr as LocationAttribute;

            if (attrName != null)
            {
                if (attrName.Location == "Header" && prop.GetValue(requestTransportationRatesFob) != null)
                {
                    string attributeName = attrName.Name;
                    numberOfColumnIterator++;

                    reportFbo.Cell($"A{numberOfColumnIterator}").Value = attributeName;

                    //Как тут скастить или сразу получить значение поля с нужным типом данных.
                    reportFbo.Cell($"B{numberOfColumnIterator}").Value = prop.GetValue(requestTransportationRatesFob).ToString();

                    continue;
                }
            }
            else 
            {
                throw new NullReferenceException();
            }
        }
    }
    ///

    wb.SaveAs(@"HelloWorld.xlsx");
}

Фрагмент класса RequestTransportationRate:

[property: Location(Location = "Header", Name = "Тип контейнера")] public string ContainerType { get; set; } = null!;
[property: Location(Location = "Header", Name = "Вид груза")] public string CargoType { get; set; } = null!;
[property: Location(Location = "Header", Name = "Загрузка в 1 контейнер брутто, кг")] public double LoadingPerContainerGross { get; set; }
[property: Location(Location = "Header", Name = "Вид упаковки")] public string PackagingType { get; set; } = null!;
[property: Location(Location = "Header", Name = "Вес 1 места, кг")] public double WeightOnePiece { get; set; }
[property: Location(Location = "Header", Name = "Мест в контейнере")] public double PlacesInContainer { get; set; }
[property: Location(Location = "Header", Name = "Адрес забора груза")] public string? CargoPickupAddress { get; set; } //FCA
[property: Location(Location = "Header", Name = "Таможенное оформление")] public string CustomsClearance { get; set; } = null!;
[property: Location(Location = "Header", Name = "Срок готовности груза")] public DateTime CargoReadinessPeriod { get; set; }
[property: Location(Location = "Header", Name = "Срок предоставления КП")] public DateTime DeadlineProvidingCP { get; set; }

Код класса атрибута:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
public class LocationAttribute : Attribute
{
    public string Location { get; set; }
    public string Name { get; set; }
}

Ответы (1 шт):

Автор решения: rotabor

Чтобы понять суть, нужно поковыряться в xslx.

введите сюда описание изображения

В нём xml, в котором всё записано строками (фрагмент из "sheet1.xml"):

<sheetData>
<row r="1" spans="1:4" x14ac:dyDescent="0.25">
<c r="A1">
<v>1</v>
</c>
<c r="B1">
<v>123.4</v>
</c>
</row>
<row r="2" spans="1:4" x14ac:dyDescent="0.25">
<c r="A2" t="s">
<v>0</v>
</c>
<c r="B2" t="s">
<v>1</v>
</c>
</row>
<row r="3" spans="1:4" x14ac:dyDescent="0.25">
<c r="A3" s="1">
<v>45627</v>
</c>
<c r="C3" t="s">
<v>1</v>
</c>
<c r="D3" s="2">
<v>45476.536805555559</v>
</c>
</row>
</sheetData>

и (фрагмент из "sharedStrings.xml"):

<si>
<t>qwer</t>
</si>
<si>
<t>frtg</t>
</si>

Итак, имеем всего три типа: число, строка и датавремя. Дальше уже нужно разбираться с библиотекой closedxml.

→ Ссылка