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);


10/04/2018

Event KeyDown not work

Event KeyDown is used in Winforms in the UI form.
Sometimes there is a problem when the event does not come.
Nothing happens when you press the keyboard keys.
Why this happens is not known.
One of the solutions to this problem is to turn on property KeyPreview.

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
 if (e.Control && e.KeyCode == Keys.O)
 {
  MessageBox.Show("Hello!");
 }
}