10/31/2018

The fastest way to generate tables in MS WORD

There are several ways to build a table in a MS Word document.
Not all of them are fast.
And some take a lot of time. Especially when the table has many lines.
I want to talk about the function ConvertToTable() that works very fast.

using System.IO;
using Microsoft.Office.Interop.Word;


//CREATING WORD AND DOCUMENT  
oApp = new Microsoft.Office.Interop.Word.Application();
oWordDoc = oApp.Documents.Open(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + @"\Test_.docx");

Range rng = oWordDoc.Bookmarks["Bmark_in_table"].Range;  

string str = "";
for (int i = 0; i < 300; i++)
{
 str = str + "111111\t22222222\t33333333\t4444444\t5555\t7777\t8888\n";
}

rng.Text = str;

object missing = System.Reflection.Missing.Value;

object f_tab = WdTableFieldSeparator.wdSeparateByTabs;
object f_colWidth = oApp.CentimetersToPoints(1.7f);
Table f_table = rng.ConvertToTable(
  ref f_tab,
  ref missing, ref missing, f_colWidth, ref missing,
  ref missing, ref missing, ref missing, ref missing,
  ref missing, ref missing, ref missing, ref missing,
  ref missing, ref missing, ref missing
 );

object File = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + @"\Test_RES.docx";
oWordDoc.SaveAs(ref File, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
oWordDoc.Close(ref missing, ref missing, ref missing);
oApp.Quit(ref missing, ref missing, ref missing);


No comments:

Post a Comment