Question

I am working with the openxml sdk and have a table to write to a word doc. Once i have written my table, is there anyway to select all the columns for that table and delete one of them based on the text for that column? For example:

foreach (var column in table.columns)
{
    if (column.Text == "Hello")
    {
       table[column].delete();
    }
}

Is there a real world implementation of the above pseudo code?

Était-ce utile?

La solution

Unfortunately, there is no concept of a "column" in a word processing table (DocumentFormat.OpenXml.WordProcessing.Table), only rows and cells. If you can assume the first row contains column names, and all rows contain the same number of cells, you can accomplish your task. One thing you have to be careful of (and one problem in your pseudocode above) is that you can't delete things from the enumeration you're currently iterating over. Here's how I would accomplish this:

var rows = table.Elements<TableRow>();
var firstRowCells = rows.ElementAt(0).Elements<TableCell>();
var cellNumbersToDelete = new List<int>();
for( int i=0; i<firstRowCells.Count(); i++ )
  if( GetCellText( firstRowCells.ElementAt( i ) ) == "Hello" )
    cellNumbersToDelete.Add( i );
foreach( var cellNumberToDelete in cellNumbersToDelete ) {
  foreach( var row in rows ) {
    cellToDelete = row.ElementAt( cellNumberToDelete );
    row.RemoveChild( cellToDelete );
  }
}

I don't have time right now to test this solution, so it'll probably require some tweaking, but it should give you a general idea about how to accomplish your task. The method GetCellText referenced above would look something like this:

string GetCellText( TableCell cell ) {
  var p = cell.Elements<Paragraph>().First();
  var r = p.Elements<Run>().First();
  var t = r.Elements<Text>().First();
  return t.Text;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top