using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.IO; using System.Data; using System.Reflection; using Word = Microsoft.Office.Interop.Word; using System.Runtime.InteropServices; using Microsoft.Office.Core; using System.Drawing; using System.Diagnostics; using System.Timers; using System.Windows.Forms; using Process = System.Diagnostics.Process; using System.Collections; using CreateTable2.Properties; namespace CreateTable2 { public partial class Form1 : Form { System.Diagnostics.Stopwatch watch; // TH, 21Jul21, to set up some global variables string RangeText; int OriginalRowCount; int OriginalColumnCount; Word.WdOrientation PageOrientation; Word.WdTableFormat TableFormat; float[] InitialColumnWidth; float FirstRowHeight, OtherRowHeight; int FirstRowHeightRule, OtherRowHeightRule; // Word.WdRowHeightRule // TH, 08Aug21, test to apply ulong type in place of Word.WdColor ulong FirstRowBackGroundColor, OtherRowBackGroundColor; // Word.WdColor int FirstRowFontBold, OtherRowFontBold; int FirstRowFontItalic, OtherRowFontItalic; string FirstRowFontName, OtherRowFontName; float FirstRowFontSize, OtherRowFontSize; int FirstRowFontUnderline, OtherRowFontUnderline; // Word.WdUnderline int BorderInsideLineStyle, BorderOutsideLineStyle; // Word.WdLineStyle int BorderInsideLineWidth, BorderOutsideLineWidth; // Word.WdLineWidth int CellVerticalAlignment; // Word.WdCellVerticalAlignment int CellHorizontalAlignment; // Word.WdParagraphAlignment private void CreateTableInWordDocument() { object oEndOfDoc = "\\endofdoc"; Word.Application objWord; Word.Document objDoc; Word.Table objTable = null; if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("CreateTableInWordDocument(): Before new Word.Application().")); objWord = new Word.Application(); if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("CreateTableInWordDocument(): After new Word.Application().")); objWord.Visible = true; object oMissing = Missing.Value; object oPassword = Missing.Value; object oTrue = true; object oFalse = false; string outputFile = Path.Combine(Path.GetDirectoryName(Settings.Default.OutputFile), Path.GetFileNameWithoutExtension(Settings.Default.OutputFile) + "_" + Settings.Default.RowCount.ToString() + "_AddRows_" + DateTime.Now.ToString("yyMMdd_hhMMssfff") + Path.GetExtension(Settings.Default.OutputFile)); string shadowyTemplate = Path.Combine(Path.GetDirectoryName(Settings.Default.WordTemplate), Path.GetFileNameWithoutExtension(Settings.Default.WordTemplate) + "_AddRows_" + DateTime.Now.ToString("yyMMdd_hhMMssfff") + Path.GetExtension(Settings.Default.WordTemplate)); File.Copy(Settings.Default.WordTemplate, shadowyTemplate); object oFilePath = shadowyTemplate; log_msg(Settings.Default.LogFile, string.Format("just before wordApp.Documents.Open(), oFilePath = ({0}).", oFilePath)); objDoc = objWord.Documents.Open(oFilePath, oMissing, oFalse, oFalse, oPassword, oMissing, oTrue, oPassword, oMissing, oMissing, oMissing, oFalse); foreach(Word.Table table in objDoc.Tables) { if (table.Title == null) continue; if (table.Title.ToUpper() != Settings.Default.TableTitle.ToUpper()) continue; objTable = table; objTable.Select(); watch = new Stopwatch(); watch.Start(); while (objTable.Rows.Count > Settings.Default.RowCount) { objTable.Rows[objTable.Rows.Count].Delete(); } while (objTable.Rows.Count < Settings.Default.RowCount) { objTable.Rows.Add(); } watch.Stop(); // TH, 20Jul21, set a repeated Header Word.Row row = table.Rows[1]; row.HeadingFormat = 0; row.HeadingFormat = -1; break; } try { objDoc.SaveAs2(outputFile, Word.WdSaveFormat.wdFormatDocumentDefault); objDoc.Close(); // var Range = objTable.ConvertToText(Separator: Microsoft.Office.Interop.Word.WdTableFieldSeparator.wdSeparateByTabs, NestedTables: true); // RangeText = Range.Text; } catch (Exception e) { MessageBox.Show("Exception: " + e.ToString()); } finally { objWord.Quit(); MessageBox.Show(string.Format("The document is saved to ({0}). It takes {1} ms.", shadowyTemplate, watch.ElapsedMilliseconds), "Saving Success", MessageBoxButtons.OK); if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("CreateTableInWordDocument(): End of the Program.")); } } private void btnGetRangeTextFromMultiTable_Click(object sender, EventArgs e) { GetRangeTextFromMultiTable(); } private void GetRangeText() { object oEndOfDoc = "\\endofdoc"; Word.Application objWord; Word.Document objDoc; Word.Table objTable = null; if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("GetRangeText(): Before new Word.Application().")); objWord = new Word.Application(); if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("GetRangeText(): After new Word.Application().")); objWord.Visible = true; object oMissing = Missing.Value; object oPassword = Missing.Value; object oTrue = true; object oFalse = false; string shadowyTemplate = Path.Combine(Path.GetDirectoryName(Settings.Default.WordTemplate), Path.GetFileNameWithoutExtension(Settings.Default.WordTemplate) + "_AddRows_" + DateTime.Now.ToString("yyMMdd_hhMMssfff") + Path.GetExtension(Settings.Default.WordTemplate)); File.Copy(Settings.Default.WordTemplate, shadowyTemplate); object oFilePath = shadowyTemplate; log_msg(Settings.Default.LogFile, string.Format("GetRangeText(): Just before wordApp.Documents.Open(), oFilePath = ({0}).", oFilePath)); objDoc = objWord.Documents.Open(oFilePath, oMissing, oFalse, oFalse, oPassword, oMissing, oTrue, oPassword, oMissing, oMissing, oMissing, oFalse); log_msg(Settings.Default.LogFile, string.Format("GetRangeText(): Just after wordApp.Documents.Open(), objDoc.Tables.Count = ({0}).", objDoc.Tables.Count)); foreach (Word.Table table in objDoc.Tables) { log_msg(Settings.Default.LogFile, string.Format("GetRangeText(): table.ID = ({0}), table.Title = ({1}), table.ToString() = ({2}).", table.ID, table.Title, table.ToString())); if (table.Title == null) continue; if (table.Title.ToUpper() != Settings.Default.TableTitle.ToUpper()) continue; objTable = table; objTable.Select(); OriginalRowCount = table.Rows.Count; OriginalColumnCount = table.Columns.Count; TableFormat = (Word.WdTableFormat)objTable.AutoFormatType; InitialColumnWidth = new float[OriginalColumnCount]; for (int col = 1; col <= OriginalColumnCount; col++) InitialColumnWidth[col - 1] = objTable.Columns[col].Width; FirstRowHeight = objTable.Rows[1].Height; FirstRowHeightRule = (int)objTable.Rows[1].HeightRule; FirstRowBackGroundColor = (ulong)objTable.Rows[1].Range.Shading.BackgroundPatternColor; FirstRowFontBold = (int)objTable.Rows[1].Range.Font.Bold; FirstRowFontItalic = (int)objTable.Rows[1].Range.Font.Italic; FirstRowFontName = objTable.Rows[1].Range.Font.Name; FirstRowFontSize = objTable.Rows[1].Range.Font.Size; FirstRowFontUnderline = (int)objTable.Rows[1].Range.Font.Underline; OtherRowHeight = objTable.Rows[2].Height; OtherRowHeightRule = (int)objTable.Rows[2].HeightRule; OtherRowFontBold = (int)objTable.Rows[2].Range.Font.Bold; OtherRowFontItalic = (int)objTable.Rows[2].Range.Font.Italic; OtherRowFontName = objTable.Rows[2].Range.Font.Name; OtherRowFontSize = objTable.Rows[2].Range.Font.Size; OtherRowFontUnderline = (int)objTable.Rows[2].Range.Font.Underline; BorderInsideLineStyle = (int)objTable.Borders.InsideLineStyle; BorderInsideLineWidth = (int)objTable.Borders.InsideLineWidth; BorderOutsideLineStyle = (int)objTable.Borders.OutsideLineStyle; BorderOutsideLineWidth = (int)objTable.Borders.OutsideLineWidth; CellVerticalAlignment = (int)objTable.Range.Cells.VerticalAlignment; CellHorizontalAlignment = (int)objTable.Range.ParagraphFormat.Alignment; Word.Range Range = objTable.ConvertToText(Separator: Word.WdTableFieldSeparator.wdSeparateByTabs, NestedTables: true); RangeText = Range.Text; PageOrientation = Range.PageSetup.Orientation; break; } try { tbxRangeText.Text = RangeText; objDoc.Close(); } catch (Exception e) { MessageBox.Show("Exception: " + e.ToString()); } finally { objWord.Quit(); MessageBox.Show("RangeText has been retrieved.", "RangeText Retrieval Success", MessageBoxButtons.OK); if (Settings.Default.Debugging == "Y") { string[] seps = { "\n" }; string[] lines = RangeText.Split(seps, StringSplitOptions.RemoveEmptyEntries); for (int l = 0; l < lines.Length; l++) log_msg(Settings.Default.LogFile, string.Format("Line {0}: ({1}).", l+1, lines[l])); } } } private void button1_Click_1(object sender, EventArgs e) { this.GenerateMultiTableByConvertToTable(); } private void GetRangeTextFromMultiTable() { string TableFilename = ""; string RowFilename = ""; string ColumnFilename = ""; List TableStringList = new List(); List RowStringList = new List(); List ColumnStringList = new List(); string[] TableStringArray; string[] RowStringArray; string[] ColumnStringArray; string ColumnString; string[] seps = { ";" }; string[] HeadBodyTables = Settings.Default.HeadBodyTables.Split(seps, StringSplitOptions.None); string[] BodyOnlyTables = Settings.Default.BodyOnlyTables.Split(seps, StringSplitOptions.None); object oEndOfDoc = "\\endofdoc"; Word.Application objWord; Word.Document objDoc; Word.Table objTable = null; if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("GetRangeTextFromMultiTable(): Before new Word.Application().")); objWord = new Word.Application(); if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("GetRangeTextFromMultiTable(): After new Word.Application().")); objWord.Visible = true; object oMissing = Missing.Value; object oPassword = Missing.Value; object oTrue = true; object oFalse = false; string shadowyTemplate = Path.Combine(Path.GetDirectoryName(Settings.Default.MultiTableTemplate), Path.GetFileNameWithoutExtension(Settings.Default.MultiTableTemplate) + "_MultiTable_" + DateTime.Now.ToString("yyMMdd_hhMMssfff") + Path.GetExtension(Settings.Default.MultiTableTemplate)); File.Copy(Settings.Default.MultiTableTemplate, shadowyTemplate); object oFilePath = shadowyTemplate; log_msg(Settings.Default.LogFile, string.Format("GetRangeTextFromMultiTable(): Just before wordApp.Documents.Open(), oFilePath = ({0}).", oFilePath)); objDoc = objWord.Documents.Open(oFilePath, oMissing, oFalse, oFalse, oPassword, oMissing, oTrue, oPassword, oMissing, oMissing, oMissing, oFalse); log_msg(Settings.Default.LogFile, string.Format("GetRangeTextFromMultiTable(): Just after wordApp.Documents.Open(), objDoc.Tables.Count = ({0}).", objDoc.Tables.Count)); foreach (Word.Table table in objDoc.Tables) { log_msg(Settings.Default.LogFile, string.Format("GetRangeTextFromMultiTable(): table.ID = ({0}), table.Title = ({1}), table.ToString() = ({2}).", table.ID, table.Title, table.ToString())); if (table.Title == null) continue; if (isStringInStrings(table.Title, HeadBodyTables)) { log_msg(Settings.Default.LogFile, string.Format("GetRangeTextFromMultiTable(): processing a HeadBody Table, Title = ({0}).", table.Title)); TableFilename = Path.Combine(Settings.Default.ParameterFolder, table.Title + "_Table.csv"); RowFilename = Path.Combine(Settings.Default.ParameterFolder, table.Title + "_Row.csv"); ColumnFilename = Path.Combine(Settings.Default.ParameterFolder, table.Title + "_Column.csv"); TableStringList.Clear(); TableStringList.Add("ColumnNumber,ConvertToText,BorderInsideLineStyle,BorderInsideLineWidth,BorderOutsideLineStyle,BorderOutsideLineWidth,CellVerticalAlignment,CellHorizontalAlignment"); RowStringList.Clear(); RowStringList.Add("Header/Body,Height,HeightRule,BackGroundColor,FontBold,FontItalic,FontName,FontSize,FontUnderline"); ColumnStringList.Clear(); objTable = table; objTable.Select(); OriginalColumnCount = table.Columns.Count; TableFormat = (Word.WdTableFormat)objTable.AutoFormatType; InitialColumnWidth = new float[OriginalColumnCount]; ColumnString = ""; for (int col = 1; col <= OriginalColumnCount; col++) { InitialColumnWidth[col - 1] = objTable.Columns[col].Width; if (col == 1) ColumnString += string.Format("{0}", InitialColumnWidth[col - 1]); else ColumnString += string.Format(",{0}", InitialColumnWidth[col - 1]); } FirstRowHeight = objTable.Rows[1].Height; FirstRowHeightRule = (int)objTable.Rows[1].HeightRule; FirstRowBackGroundColor = (ulong)objTable.Rows[1].Range.Shading.BackgroundPatternColor; FirstRowFontBold = (int)objTable.Rows[1].Range.Font.Bold; FirstRowFontItalic = (int)objTable.Rows[1].Range.Font.Italic; FirstRowFontName = objTable.Rows[1].Range.Font.Name; FirstRowFontSize = objTable.Rows[1].Range.Font.Size; FirstRowFontUnderline = (int)objTable.Rows[1].Range.Font.Underline; OtherRowHeight = objTable.Rows[2].Height; OtherRowHeightRule = (int)objTable.Rows[2].HeightRule; OtherRowBackGroundColor = (ulong)objTable.Rows[2].Range.Shading.BackgroundPatternColor; OtherRowFontBold = (int)objTable.Rows[2].Range.Font.Bold; OtherRowFontItalic = (int)objTable.Rows[2].Range.Font.Italic; OtherRowFontName = objTable.Rows[2].Range.Font.Name; OtherRowFontSize = objTable.Rows[2].Range.Font.Size; OtherRowFontUnderline = (int)objTable.Rows[2].Range.Font.Underline; BorderInsideLineStyle = (int)objTable.Borders.InsideLineStyle; BorderInsideLineWidth = (int)objTable.Borders.InsideLineWidth; BorderOutsideLineStyle = (int)objTable.Borders.OutsideLineStyle; BorderOutsideLineWidth = (int)objTable.Borders.OutsideLineWidth; CellVerticalAlignment = (int)objTable.Range.Cells.VerticalAlignment; CellHorizontalAlignment = (int)objTable.Range.ParagraphFormat.Alignment; Word.Range Range = objTable.ConvertToText(Separator: Word.WdTableFieldSeparator.wdSeparateByTabs, NestedTables: true); RangeText = Range.Text; TableStringList.Add(string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", OriginalColumnCount, RangeText, BorderInsideLineStyle, BorderInsideLineWidth, BorderOutsideLineStyle, BorderOutsideLineWidth, CellVerticalAlignment, CellHorizontalAlignment)); TableStringArray = ConvertListToStringArray(TableStringList); File.WriteAllLines(TableFilename, TableStringArray); ColumnStringList.Add(ColumnString); ColumnStringArray = ConvertListToStringArray(ColumnStringList); File.WriteAllLines(ColumnFilename, ColumnStringArray); // TH, 02Aug21, 23:01 // RowStringList.Add("Header/Body,Height,HeightRule,BackGroundColor,FontBold,FontItalic,FontName,FontSize,FontUnderline"); RowStringList.Add(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}","Header", FirstRowHeight, FirstRowHeightRule, FirstRowBackGroundColor, FirstRowFontBold, FirstRowFontItalic, FirstRowFontName, FirstRowFontSize, FirstRowFontUnderline)); RowStringList.Add(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}", "Body", OtherRowHeight, OtherRowHeightRule, OtherRowBackGroundColor, OtherRowFontBold, OtherRowFontItalic, OtherRowFontName, OtherRowFontSize, OtherRowFontUnderline)); RowStringArray = ConvertListToStringArray(RowStringList); File.WriteAllLines(RowFilename, RowStringArray); } else if (isStringInStrings(table.Title, BodyOnlyTables)) { log_msg(Settings.Default.LogFile, string.Format("GetRangeTextFromMultiTable(): handling a BodyOnly Table, Title = ({0}).", table.Title)); TableFilename = Path.Combine(Settings.Default.ParameterFolder, table.Title + "_Table.csv"); RowFilename = Path.Combine(Settings.Default.ParameterFolder, table.Title + "_Row.csv"); ColumnFilename = Path.Combine(Settings.Default.ParameterFolder, table.Title + "_Column.csv"); TableStringList.Clear(); TableStringList.Add("ColumnNumber,ConvertToText,BorderInsideLineStyle,BorderInsideLineWidth,BorderOutsideLineStyle,BorderOutsideLineWidth,CellVerticalAlignment,CellHorizontalAlignment"); RowStringList.Clear(); RowStringList.Add("Header/Body,Height,HeightRule,BackGroundColor,FontBold,FontItalic,FontName,FontSize,FontUnderline"); ColumnStringList.Clear(); objTable = table; objTable.Select(); OriginalColumnCount = table.Columns.Count; TableFormat = (Word.WdTableFormat)objTable.AutoFormatType; InitialColumnWidth = new float[OriginalColumnCount]; ColumnString = ""; for (int col = 1; col <= OriginalColumnCount; col++) { InitialColumnWidth[col - 1] = objTable.Columns[col].Width; if (col == 1) ColumnString += string.Format("{0}", InitialColumnWidth[col - 1]); else ColumnString += string.Format(",{0}", InitialColumnWidth[col - 1]); } OtherRowHeight = objTable.Rows[1].Height; OtherRowHeightRule = (int)objTable.Rows[1].HeightRule; OtherRowBackGroundColor = (ulong)objTable.Rows[1].Range.Shading.BackgroundPatternColor; OtherRowFontBold = (int)objTable.Rows[1].Range.Font.Bold; OtherRowFontItalic = (int)objTable.Rows[1].Range.Font.Italic; OtherRowFontName = objTable.Rows[1].Range.Font.Name; OtherRowFontSize = objTable.Rows[1].Range.Font.Size; OtherRowFontUnderline = (int)objTable.Rows[1].Range.Font.Underline; BorderInsideLineStyle = (int)objTable.Borders.InsideLineStyle; BorderInsideLineWidth = (int)objTable.Borders.InsideLineWidth; BorderOutsideLineStyle = (int)objTable.Borders.OutsideLineStyle; BorderOutsideLineWidth = (int)objTable.Borders.OutsideLineWidth; CellVerticalAlignment = (int)objTable.Range.Cells.VerticalAlignment; CellHorizontalAlignment = (int)objTable.Range.ParagraphFormat.Alignment; Word.Range Range = objTable.ConvertToText(Separator: Word.WdTableFieldSeparator.wdSeparateByTabs, NestedTables: true); RangeText = Range.Text; TableStringList.Add(string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", OriginalColumnCount, RangeText, BorderInsideLineStyle, BorderInsideLineWidth, BorderOutsideLineStyle, BorderOutsideLineWidth, CellVerticalAlignment, CellHorizontalAlignment)); TableStringArray = ConvertListToStringArray(TableStringList); File.WriteAllLines(TableFilename, TableStringArray); ColumnStringList.Add(ColumnString); ColumnStringArray = ConvertListToStringArray(ColumnStringList); File.WriteAllLines(ColumnFilename, ColumnStringArray); // TH, 02Aug21, 23:01 // RowStringList.Add("Header/Body,Height,HeightRule,BackGroundColor,FontBold,FontItalic,FontName,FontSize,FontUnderline"); RowStringList.Add(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}", "Body", OtherRowHeight, OtherRowHeightRule, OtherRowBackGroundColor, OtherRowFontBold, OtherRowFontItalic, OtherRowFontName, OtherRowFontSize, OtherRowFontUnderline)); RowStringArray = ConvertListToStringArray(RowStringList); File.WriteAllLines(RowFilename, RowStringArray); } continue; } try { objDoc.Close(); } catch (Exception e) { MessageBox.Show("Exception: " + e.ToString()); } finally { objWord.Quit(); MessageBox.Show("RangeText has been retrieved.", "RangeText Retrieval Success", MessageBoxButtons.OK); } } private static string[] ConvertListToStringArray(List myList) { string[] myArray = new string[myList.Count]; for (int l = 0; l < myList.Count; l++) { myArray[l] = myList[l]; } return (myArray); } private void btnMergeTable_Click(object sender, EventArgs e) { MergeTable(); } private void GenerateByConvertToTable() { object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; Word.Application objWord; Word.Document objDoc; if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("GenerateByConvertToTable(): Before new Word.Application().")); objWord = new Word.Application(); if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("GenerateByConvertToTable(): After new Word.Application().")); objWord.Visible = true; objDoc = objWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); watch = new System.Diagnostics.Stopwatch(); watch.Start(); string NewRangeText = RangeText; int TabsNum = (Settings.Default.RowCount - OriginalRowCount) * OriginalColumnCount; for (int t = 0; t < TabsNum; t++) NewRangeText += "\t"; Word.Range wrdRng = objDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.PageSetup.Orientation = PageOrientation; wrdRng.Text = NewRangeText; var objTable = wrdRng.ConvertToTable(Separator: Word.WdTableFieldSeparator.wdSeparateByTabs, NumColumns: OriginalColumnCount, NumRows: Settings.Default.RowCount, DefaultTableBehavior: Word.WdDefaultTableBehavior.wdWord9TableBehavior, AutoFitBehavior: Word.WdAutoFitBehavior.wdAutoFitWindow, ApplyHeadingRows: true, ApplyBorders: true, ApplyShading: true, ApplyFont: true, ApplyColor: true ); // TH, 21Jul21, set the properties of all rows, then apply first-row properties to overwrite objTable.Rows.Height = OtherRowHeight; objTable.Rows.HeightRule = (Word.WdRowHeightRule)OtherRowHeightRule; objTable.Range.Font.Bold = OtherRowFontBold; objTable.Range.Font.Italic = OtherRowFontItalic; objTable.Range.Font.Name = OtherRowFontName; objTable.Range.Font.Size = OtherRowFontSize; objTable.Range.Font.Underline = (Word.WdUnderline)OtherRowFontUnderline; // TH, 20Jul21, set a repeated Header Word.Row row = objTable.Rows[1]; row.HeadingFormat = 0; row.HeadingFormat = -1; row.Height = FirstRowHeight; row.HeightRule = (Word.WdRowHeightRule)FirstRowHeightRule; row.Range.Shading.BackgroundPatternColor = (Word.WdColor)FirstRowBackGroundColor; row.Range.Font.Bold = FirstRowFontBold; row.Range.Font.Italic = FirstRowFontItalic; row.Range.Font.Name = FirstRowFontName; row.Range.Font.Size = FirstRowFontSize; row.Range.Font.Underline = (Word.WdUnderline)FirstRowFontUnderline; objTable.Borders.InsideLineStyle = (Word.WdLineStyle)BorderInsideLineStyle; objTable.Borders.InsideLineWidth = (Word.WdLineWidth)BorderInsideLineWidth; objTable.Borders.OutsideLineStyle = (Word.WdLineStyle)BorderOutsideLineStyle; objTable.Borders.OutsideLineWidth = (Word.WdLineWidth)BorderOutsideLineWidth; objTable.Range.Cells.VerticalAlignment = (Word.WdCellVerticalAlignment)CellVerticalAlignment; objTable.Range.ParagraphFormat.Alignment = (Word.WdParagraphAlignment)CellHorizontalAlignment; for(int col = 1; col <= objTable.Columns.Count; col++) objTable.Columns[col].Width = InitialColumnWidth[col - 1]; try { watch.Stop(); } catch (Exception e) { MessageBox.Show("Exception: " + e.ToString()); } finally { string filename = Path.Combine(Path.GetDirectoryName(Settings.Default.OutputFile), Path.GetFileNameWithoutExtension(Settings.Default.OutputFile) + "_" + Settings.Default.RowCount.ToString() + "_ConvertToTable_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + Path.GetExtension(Settings.Default.OutputFile)); objDoc.SaveAs2(filename, Word.WdSaveFormat.wdFormatDocumentDefault); objDoc.Close(); objWord.Quit(); MessageBox.Show(string.Format("It takes {0} ms to save the document to ({1}).", watch.ElapsedMilliseconds, filename), "Saving Document OK", MessageBoxButtons.OK); if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("GenerateByConvertToTable(): End of the Program.")); } } private void GenerateMultiTableByConvertToTable() { string TableFilename = ""; object oEndOfDoc = "\\endofdoc"; Word.Application objWord; Word.Document objDoc; Word.Table objTable = null; if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("GenerateMultiTableByConvertToTable(): Before new Word.Application().")); objWord = new Word.Application(); if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("GenerateMultiTableByConvertToTable(): After new Word.Application().")); objWord.Visible = true; object oMissing = Missing.Value; object oPassword = Missing.Value; object oTrue = true; object oFalse = false; string shadowyTemplate = Path.Combine(Path.GetDirectoryName(Settings.Default.MultiTableTemplate), Path.GetFileNameWithoutExtension(Settings.Default.MultiTableTemplate) + "_Output_" + DateTime.Now.ToString("yyMMdd_hhMMssfff") + Path.GetExtension(Settings.Default.MultiTableTemplate)); File.Copy(Settings.Default.MultiTableTemplate, shadowyTemplate); object oFilePath = shadowyTemplate; log_msg(Settings.Default.LogFile, string.Format("GenerateMultiTableByConvertToTable(): Just before wordApp.Documents.Open(), oFilePath = ({0}).", oFilePath)); objDoc = objWord.Documents.Open(oFilePath, oMissing, oFalse, oFalse, oPassword, oMissing, oTrue, oPassword, oMissing, oMissing, oMissing, oFalse); log_msg(Settings.Default.LogFile, string.Format("GenerateMultiTableByConvertToTable(): Just after wordApp.Documents.Open(), objDoc.Tables.Count = ({0}).", objDoc.Tables.Count)); foreach (Word.Table table in objDoc.Tables) { log_msg(Settings.Default.LogFile, string.Format("GenerateMultiTableByConvertToTable(): table.ID = ({0}), table.Title = ({1}), table.ToString() = ({2}).", table.ID, table.Title, table.ToString())); if (table.Title == null) continue; TableFilename = Path.Combine(Settings.Default.RangeTextFolder, table.Title + ".txt"); if (!File.Exists(TableFilename)) continue; string content = File.ReadAllText(TableFilename); string[] seps = { "," }; string[] parts = content.Split(seps, StringSplitOptions.None); OriginalColumnCount = Convert.ToInt32(parts[0]); RangeText = parts[1]; Word.Range Range = table.Range; table.Delete(); Range.Text = RangeText; objTable = Range.ConvertToTable(Separator: Word.WdTableFieldSeparator.wdSeparateByTabs, NumColumns: OriginalColumnCount, DefaultTableBehavior: Word.WdDefaultTableBehavior.wdWord9TableBehavior, AutoFitBehavior: Word.WdAutoFitBehavior.wdAutoFitWindow, ApplyHeadingRows: true, ApplyBorders: true, ApplyShading: true, ApplyFont: true, ApplyColor: true ); continue; } try { objDoc.Close(); } catch (Exception e) { MessageBox.Show("Exception: " + e.ToString()); } finally { objWord.Quit(); MessageBox.Show("RangeText has been retrieved.", "RangeText Retrieval Success", MessageBoxButtons.OK); } } private void DeleteParagraph() { object oEndOfDoc = "\\endofdoc"; Word.Application objWord; Word.Document objDoc; int count = 0; if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("DeleteParagraph(): Before new Word.Application().")); objWord = new Word.Application(); if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("DeleteParagraph(): After new Word.Application().")); objWord.Visible = true; object oMissing = Missing.Value; object oPassword = Missing.Value; object oTrue = true; object oFalse = false; string shadowyTemplate = Path.Combine(Path.GetDirectoryName(Settings.Default.SplitTableDoc), Path.GetFileNameWithoutExtension(Settings.Default.SplitTableDoc) + "_DeleteParagraph_" + DateTime.Now.ToString("yyMMdd_hhMMssfff") + Path.GetExtension(Settings.Default.SplitTableDoc)); File.Copy(Settings.Default.SplitTableDoc, shadowyTemplate); object oFilePath = shadowyTemplate; log_msg(Settings.Default.LogFile, string.Format("DeleteParagraph(): Just before wordApp.Documents.Open(), oFilePath = ({0}).", oFilePath)); objDoc = objWord.Documents.Open(oFilePath, oMissing, oFalse, oFalse, oPassword, oMissing, oTrue, oPassword, oMissing, oMissing, oMissing, oFalse); log_msg(Settings.Default.LogFile, string.Format("DeleteParagraph(): Just after wordApp.Documents.Open(), objDoc.Tables.Count = ({0}).", objDoc.Tables.Count)); // TH, 02Aug21, do trials to merge tables by deleting a separating paragraph string[] seps = { ";" }; string[] DeleteLastParagraphTables = Settings.Default.DeleteLastParagraphTables.Split(seps, StringSplitOptions.None); string[] DeleteFirstParagraphTables = Settings.Default.DeleteFirstParagraphTables.Split(seps, StringSplitOptions.None); foreach (Word.Table table in objDoc.Tables) { log_msg(Settings.Default.LogFile, string.Format("DeleteParagraph(): table.ID = ({0}), table.Title = ({1}), table.ToString() = ({2}).", table.ID, table.Title, table.ToString())); if (table.Title == null) continue; if(isStringInStrings(table.Title, DeleteLastParagraphTables)) { count = table.Range.Paragraphs.Count; table.Range.Paragraphs[count].Range.Delete(Type.Missing, Type.Missing); } else if (isStringInStrings(table.Title, DeleteFirstParagraphTables)) { table.Range.Paragraphs[1].Range.Delete(Type.Missing, Type.Missing); } } try { objDoc.Close(); } catch (Exception e) { MessageBox.Show("Exception: " + e.ToString()); } finally { objWord.Quit(); MessageBox.Show("Split tables have been merged.", "SplitTable Merging Success", MessageBoxButtons.OK); } } private void btnDeleteParagraph_Click(object sender, EventArgs e) { DeleteParagraph(); } private void MergeTable() { object oEndOfDoc = "\\endofdoc"; Word.Application objWord; Word.Document objDoc; if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("MergeTable(): Before new Word.Application().")); objWord = new Word.Application(); if (Settings.Default.Debugging == "Y") log_msg(Settings.Default.LogFile, string.Format("MergeTable(): After new Word.Application().")); objWord.Visible = true; object oMissing = Missing.Value; object oPassword = Missing.Value; object oTrue = true; object oFalse = false; string outputFile = Path.Combine(Path.GetDirectoryName(Settings.Default.SplitTableDoc), Path.GetFileNameWithoutExtension(Settings.Default.SplitTableDoc) + "_Output_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + Path.GetExtension(Settings.Default.SplitTableDoc)); object oFilePath = Settings.Default.SplitTableDoc; log_msg(Settings.Default.LogFile, string.Format("MergeTable(): Just before wordApp.Documents.Open(), oFilePath = ({0}).", oFilePath)); objDoc = objWord.Documents.Open(oFilePath, oMissing, oFalse, oFalse, oPassword, oMissing, oTrue, oPassword, oMissing, oMissing, oMissing, oFalse); log_msg(Settings.Default.LogFile, string.Format("MergeTable(): Just after wordApp.Documents.Open(), objDoc.Tables.Count = ({0}).", objDoc.Tables.Count)); string[] seps = { ";" }; string[] TableGapTexts = Settings.Default.TableGapText.Split(seps, StringSplitOptions.None); foreach (string gap_text in TableGapTexts) { log_msg(Settings.Default.LogFile, string.Format("MergeTable(): will delete the range of TableGapText ({0}).", gap_text)); deleteGapText(objDoc, gap_text); } try { objDoc.SaveAs2(outputFile, Word.WdSaveFormat.wdFormatDocumentDefault); objDoc.Close(); } catch (Exception e) { MessageBox.Show("Exception: " + e.ToString()); } finally { objWord.Quit(); MessageBox.Show("SplitTable has been merged.", "SplitTable Merging Success", MessageBoxButtons.OK); } } void deleteGapText(Word.Document doc, string txt) { object missing = System.Reflection.Missing.Value; doc.Content.Find.ClearFormatting(); object keyword = txt.ToString(); if (doc.Content.Find.Execute(ref keyword, 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)) { var range = doc.Content; if (range.Find.Execute(txt)) { range.Expand(Word.WdUnits.wdParagraph); // or change to .wdSentence or .wdLine range.Delete(); // TH, 04Aug21, to completely merge the two adjacent tables range.Expand(Word.WdUnits.wdParagraph); // or change to .wdSentence or .wdLine range.Delete(); // Word.Paragraph para = app.Selection.Range.Paragraphs[1]; // tbl.Rows.WrapAroundText = -1; } } else { log_msg(Settings.Default.LogFile, string.Format("deleteGapText(): TableGapText ({0}) cannot be found.", txt)); } } private void deleteBookmarkRange(Word.Document Doc, string bookmark) { Word.Range range = Doc.Range(); range.Start = Doc.Bookmarks.get_Item(bookmark).Range.Start; range.End = Doc.Bookmarks.get_Item(bookmark).Range.End; range.Delete(Type.Missing, Type.Missing); } public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.CreateTableInWordDocument(); } private void Form1_Load(object sender, EventArgs e) { } // TH, 12Jul21, for debugging purpose private void log_msg(string filename, string msg) { string myPath = string.Empty; myPath = Path.GetDirectoryName(filename); filename = Path.Combine(myPath, Path.GetFileNameWithoutExtension(filename) + "_" + DateTime.Now.ToString("yyMMdd") + Path.GetExtension(filename)); if (!string.IsNullOrEmpty(filename)) { if (!Directory.Exists(myPath)) Directory.CreateDirectory(myPath); if (File.Exists(filename)) { // Append to existing file. using (StreamWriter sw = File.AppendText(filename)) { sw.WriteLine("\r\n" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss.fff") + " - " + msg); } } else { // Create a file to write to. using (StreamWriter sw = File.CreateText(filename)) { sw.WriteLine(DateTime.Now.ToString("yyyyMMdd HH:mm:ss.fff") + " - " + msg); } } } } private void button3_Click(object sender, EventArgs e) { this.Close(); } private void btnConvertToText_Click(object sender, EventArgs e) { this.GenerateByConvertToTable(); } private void btnGetRangeText_Click(object sender, EventArgs e) { this.GetRangeText(); } private bool isStringInStrings(string str, string[] values) { bool res = false; for (int v = 0; v < values.Length; v++) { if (str == values[v]) { res = true; break; } } return (res); } } }