Search code examples
c#openxmlopenxml-sdkopenxml-table

Using open xml sdk code, how to resize a table (in ms word document) to fit into table contents?


In MS Words, to make the columns in a table automatically fit the contents, we click on the table. On the Layout tab, in the Cell Size group, click AutoFit, and then click AutoFit Contents.

For example : enter image description here

After applying AutoFit to Content, here's the result :

enter image description here

I am using Microsoft Open XML SDK to implement above feature. I have created a method to group my table cells by columns and then I set each column width to the largest cell content length.

But the issue is, some cells are either merged horizontally or vertically (That's where lays my main issue), making my solution an absolute fiasco. I searched everywhere, but I did not find some helpful resources

After an extensive search spanning several days, I have exhausted my efforts and decided to seek assistance by posing my question on this forum. Having familiarized myself with the forum's guidelines on asking questions, I am now presenting my query and kindly requesting suggestions for a solution.


Solution

  • I've finally figured out the solution.

    As per Open Office XML documentation on Tables detailled at : http://officeopenxml.com/WPtableLayout.php :

    enter image description here

    So, basically setting my tables properties TableLayout and TableWidth properties to AutoFit and Auto did the trick.

    An additional change I also needed to operate is to set the table and cells width and type to '0' and 'Auto' as in MS Words when using AutoFit to Contents options.

    Here's my final solution :

      public static class OpenXmlAutoFit
      {
        public static void AutoFitToContent( string filePath, string copyPath )
        {
          // Check if the source file exists
          if( File.Exists( filePath ) )
          {
            // Check if the copy file already exists
            if( File.Exists( copyPath ) )
            {
              // Delete the existing copy file
              File.Delete( copyPath );
            }
    
            // Create a new copy of the file
            File.Copy( filePath, copyPath );
          }
    
          using( WordprocessingDocument doc = WordprocessingDocument.Open( copyPath, true ) )
          {
            MainDocumentPart mainPart = doc.MainDocumentPart;
            IEnumerable<DocumentFormat.OpenXml.Wordprocessing.Table> tables = mainPart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Table>();
            // var tables = mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Drawing.Table>();
            // var tables = mainPart.Document.Body.Descendants<Table>();
    
    
            foreach( var table in tables )
            {
              if( table != null )
              {
                // Get the table properties element
                TableProperties tableProperties = table.GetFirstChild<TableProperties>();
    
                // If table properties exist, update them; otherwise, create new table properties
                if( tableProperties != null )
                {
                  // Update existing table properties
                  tableProperties.TableLayout = new TableLayout { Type = TableLayoutValues.Autofit };
                  tableProperties.TableWidth = new TableWidth { Type = TableWidthUnitValues.Auto };
                }
                else
                {
                  // Create new table properties and add them to the table
                  tableProperties = new TableProperties(
                      new TableLayout { Type = TableLayoutValues.Autofit },
                      new TableWidth { Type = TableWidthUnitValues.Auto }
                  );
                  table.PrependChild( tableProperties );
                }
    
                var tableWidths = table.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableWidth>().ToList();
                foreach( var tblW in tableWidths )
                {
                  tblW.Width = "0";
                  tblW.Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Auto;
                }
    
                var tableCellsWidths = table.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCellWidth>().ToList();
                foreach( var tcW in tableCellsWidths )
                {
                  tcW.Width = "0";
                  tcW.Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Auto;
                }
              }
            }
    
            mainPart.Document.Save();
          }
        }
      }