If you’re allowed to use ClosedXml you can do something like this
private static IReadOnlyCollection<Planet> GetPlanets()
{
// open the workbook
var workbook = new XLWorkbook("Book1.xlsx");
var sheet1 = workbook.Worksheet(1);
var headers = sheet1.Row(1);
var headersCount = headers.Cells().Count(cell => !cell.IsEmpty());
var planets = new List<Planet>();
// loop around each header
for (int i = 2; i < headersCount + 3; i=i+2)
{
var name = headers.Cell(i).Value?.ToString();
if (string.IsNullOrEmpty(name))
{
break;
}
var produced = new Produced(
int.Parse(sheet1.Cell(3, i).Value?.ToString()),
int.Parse(sheet1.Cell(4, i).Value?.ToString())
);
var sold = new Sold(
int.Parse(sheet1.Cell(3, i + 1).Value?.ToString()),
int.Parse(sheet1.Cell(4, i + 1).Value?.ToString())
);
planets.Add(new Planet(
name,
produced,
sold
));
}
return planets;
}
where
public sealed record Planet(string? Name, Produced Produced, Sold Sold);
public sealed record Produced(int TeddyBears, int BoardGames) : Metric(TeddyBears, BoardGames);
public sealed record Sold(int TeddyBears, int BoardGames) : Metric(TeddyBears, BoardGames);
public abstract record Metric(int TeddyBears, int BoardGames);
This of course assumes the exact structure from your example, but its easy to configure it to do whatever you need
2
Answers
If you’re allowed to use ClosedXml you can do something like this
where
This of course assumes the exact structure from your example, but its easy to configure it to do whatever you need
using IronXL Library it will be very easy as you can see in the following code sample