C
C#2y ago
MeHow

❔ DocumentFormat.OpenXML - insert row into an Excel Table

Hi, I have a problem with inserting a row into the Table in Excel document. I had no problems with inserting cell values, but when I want to add a collection of objects as rows it does not update the table. Here's the code:
void InsertDeskIntoATable(Table table, Desk desk)
{
var row = new TableRow();

var props = desk.GetType().GetProperties();

foreach (var prop in props)
{
var value = prop.GetValue(desk, null) ?? 0;
var cell = new TableCell(new Paragraph(new Run(new Text(value.ToString()))));
row.Append(cell);
}

table.Append(row);
table.Save();
}

public class Desk
{
public int Width { get; set; }
public int Height { get; set; }
}
void InsertDeskIntoATable(Table table, Desk desk)
{
var row = new TableRow();

var props = desk.GetType().GetProperties();

foreach (var prop in props)
{
var value = prop.GetValue(desk, null) ?? 0;
var cell = new TableCell(new Paragraph(new Run(new Text(value.ToString()))));
row.Append(cell);
}

table.Append(row);
table.Save();
}

public class Desk
{
public int Width { get; set; }
public int Height { get; set; }
}
I'm using reflections cause I want to make the function generic in the future, it works fine but the table in my file does not update. The reference to the table is correct and the other data saves properly. Just not the table 🙂
3 Replies
canton7
canton72y ago
OpenXML and Excel is just painful. There's so much boilerplate and weird special cases you need to handle There are wrappers around OpenXML for Excel which make life so much easier. ClosedXML is one I've used, but IIRC the OpenXML repo lists others. I strongly recommend using one (OpenXML for Word is sensible enough to tackle on your own)
canton7
canton72y ago
GitHub
GitHub - dotnet/Open-XML-SDK: Open XML SDK by Microsoft
Open XML SDK by Microsoft. Contribute to dotnet/Open-XML-SDK development by creating an account on GitHub.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server