I want to add a table with my Word Add-in with data from my database.
I've done that successfully but now I have a problem with the position of the table.
I want to place it exactly where my current position in the Word document is.
But so it's always added at the beginning.
Does anyone know how to adjust the range that my start value is always my current position?
This is a part of my code:
private void createTable_Click(object sender, EventArgs e) {
object start = 0, end = 0;
Word.Document document = Globals.ThisAddIn.Application.ActiveDocument;
Word.Range rng = document.Range(ref start, ref end);
// Insert a title for the table and paragraph marks.
rng.InsertBefore("List");
rng.Font.Name = "Verdana";
rng.Font.Size = 16;
rng.InsertParagraphAfter();
rng.InsertParagraphAfter();
rng.SetRange(rng.End, rng.End);
// Add the table.
rng.Tables.Add(document.Paragraphs[2].Range, 1, 7, ref missing, ref missing);
// Format the table and apply a style.
Word.Table tbl = document.Tables[1]; tbl.Range.Font.Size = 8;
tbl.Borders[WdBorderType.wdBorderLeft].LineStyle =
WdLineStyle.wdLineStyleSingle;
tbl.Borders[WdBorderType.wdBorderRight].LineStyle =
WdLineStyle.wdLineStyleSingle;
tbl.Borders[WdBorderType.wdBorderTop].LineStyle =
WdLineStyle.wdLineStyleSingle;
tbl.Borders[WdBorderType.wdBorderBottom].LineStyle =
WdLineStyle.wdLineStyleSingle;
tbl.Borders[WdBorderType.wdBorderHorizontal].LineStyle =
WdLineStyle.wdLineStyleSingle;
tbl.Borders[WdBorderType.wdBorderVertical].LineStyle =
WdLineStyle.wdLineStyleSingle;
tbl.Borders[WdBorderType.wdBorderBottom].Color = WdColor.wdColorBlack; tbl.Rows.Alignment = WdRowAlignment.wdAlignRowCenter; tbl.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitWindow);
On re-reading... To insert at the current position - if you mean where the cursor is:
Word.Range rngSel = wdApp.Selection.Range;
rngSel.Tables.Add(//params here);
Otherwise, if you mean at the end of the information being inserted byy the code, instead of these two lines
rng.InsertBefore("List");
rng.Font.Name = "Verdana";
rng.Font.Size = 16;
rng.InsertParagraphAfter();
rng.InsertParagraphAfter();
rng.SetRange(rng.End, rng.End);
Use
rng.Text = "List\n\n"
rng.Font.Name = "Verdana";
rng.Font.Size = 16;
rng.Collapse(WdCollapseDirection.wdCollapseEnd);
\n inserts a new paragraph (carriage return) and can be included as part of a string.
Assigning text directly to the Range and working with the Collapse method is (in my opinion) a bit more predictable than the various Insert methods. Some of the Insert methods include what's inserted in the range, others do not.
FWIW when it's not clear what the problem might be it can help to put a rng.Select(); at a key point in the code and comment out the rest of the lines so that the code ends with the range in question visible. That can often be informative as to the origin of a problem with a range.
Related
I have created a 1x3 table as my header in word. This is how I want it to look like.
LeftText MiddleText PageNumber:
I want the PageNumber cell to look like this -
Page: X of Y
I have managed to do cell (1,1) and (1,2). I found this to help me with cell (1,3) but it is not working as I like. I know how to get the total count of the document. I'm not sure how to implement it properly.
Range rRange = restheaderTable.Cell(1, 3).Range;
rRange.End = rRange.End - 1;
oDoc.Fields.Add(rRange, Type: WdFieldType.wdFieldPage, Text: "Page Number: ");
I can't even get the Text "Page Number: " to display in the cell. All it has is a number right now.
The field enumeration you're looking for is WordWdFieldType.wdFieldNumPages.
The next hurdle is how to construct field + text + field as Word doesn't behave "logically" when things are added in this order. The target point remains before the field that's inserted. So it's either necessary to work backwards, or to move the target range after each bit of content.
Here's some code I have the demonstrates the latter approach. Inserting text and inserting fields are in two separate procedures that take the target Range and the text (whether literal or the field text) as parameters. This way the field code can be built up logically (Page x of n). The target Range is returned from both procedures, already collapsed to its end-point, ready for appending further content.
Note that I prefer to construct a field using the field's text (including any field switches) rather than specifying a field type (the WdFieldType enumeration). This provides greater flexibility. I also highly recommend setting the PreserveFormatting parameter to false as the true setting can result in very odd formatting when fields are updated. It should only be used in very specific instances (usually involving linked tables).
private void btnInsertPageNr_Click(object sender, EventArgs e)
{
getWordInstance();
Word.Document doc = null;
if (wdApp.Documents.Count > 0)
{
doc = wdApp.ActiveDocument;
Word.Range rngHeader = doc.Sections[1].Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
if (rngHeader.Tables.Count > 0)
{
Word.Table tbl = rngHeader.Tables[1];
Word.Range rngPageNr = tbl.Range.Cells[tbl.Range.Cells.Count].Range;
//Collapse the range so that it's within the cell and
//doesn't include the end-of-cell markers
object oCollapseStart = Word.WdCollapseDirection.wdCollapseStart;
rngPageNr.Collapse(ref oCollapseStart);
rngPageNr = InsertNewText(rngPageNr, "Page ");
rngPageNr = InsertAField(rngPageNr, "Page");
rngPageNr = InsertNewText(rngPageNr, " of ");
rngPageNr = InsertAField(rngPageNr, "NumPages");
}
}
}
private Word.Range InsertNewText(Word.Range rng, string newText)
{
object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
rng.Text = newText;
rng.Collapse(ref oCollapseEnd);
return rng;
}
private Word.Range InsertAField(Word.Range rng,
string fieldText)
{
object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
object unitCharacter = Word.WdUnits.wdCharacter;
object oOne = 1;
Word.Field fld = rng.Document.Fields.Add(rng, missing, fieldText, false);
Word.Range rngField = fld.Result;
rngField.Collapse(ref oCollapseEnd);
rngField.MoveStart(ref unitCharacter, ref oOne);
return rngField;
}
I'm splitting a cell into two columns:
table.Cell(1,1).Split(1,2);
How can I access the two new cells?
As with many things in Word, the trick to getting "pointers" to objects is to work with Ranges.
In this case, if a Range to the original cell is instantiated it's possible to refer back to it. After the split it will be in the first cell. From it, it's possible to get both the first and second cells (and, indeed, anything else in the table).
For example
Word.Table tbl = document.Tables[1];
Word.Cell cel = tbl.Cell(1, 1);
Word.Range rng = cel.Range;
cel.Split(1, 2);
//At this point, rng is at the start of the first (left-most) cell of the two
//using new objects for the split cells
Word.Cell newCel1 = rng.Cells[1];
Word.Cell newCel2 = rng.Next(wdCell, 1).Cells[1];
newCel1.Range.Text = "1";
newCel2.Range.Text = "2";
//Alternative: using the original cell, plus a new object for the split cell
//Word.Cell newCel2 = rng.Next(Word.WdUnits.wdCell, 1).Cells[1];
//cel.Range.Text = "1";
//newCel2.Range.Text = "2";
Using Excel Interop, I can configure a sheet for printing with code like this:
_xlSheetPlatypus.PageSetup.PrintArea = "A1:" +
GetExcelTextColumnName(
_xlSheetPlatypus.UsedRange.Columns.Count) +
_xlSheetPlatypus.UsedRange.Rows.Count;
_xlSheetPlatypus.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape;
_xlSheetPlatypus.PageSetup.Zoom = false;
_xlSheetPlatypus.PageSetup.FitToPagesWide = 1;
_xlSheetPlatypus.PageSetup.FitToPagesTall = 100;
_xlSheetPlatypus.PageSetup.LeftMargin = _xlApp.Application.InchesToPoints(0.5);
_xlSheetPlatypus.PageSetup.RightMargin = _xlApp.Application.InchesToPoints(0.5);
_xlSheetPlatypus.PageSetup.TopMargin = _xlApp.Application.InchesToPoints(0.5);
_xlSheetPlatypus.PageSetup.BottomMargin = _xlApp.Application.InchesToPoints(0.5);
_xlSheetPlatypus.PageSetup.HeaderMargin = _xlApp.Application.InchesToPoints(0.5);
_xlSheetPlatypus.PageSetup.FooterMargin = _xlApp.Application.InchesToPoints(0.5);
_xlSheetPlatypus.PageSetup.PrintTitleRows = String.Format("${0}:${0}", CUSTOMER_HEADING_ROW);
I think I can pretty much emulate that with Spreadsheet Light with this code:
SLPageSettings ps = new SLPageSettings();
// PrintArea
// ???
// PrintTitleRows
ps.PrintHeadings = true;
ps.SetCenterHeaderText(String.Format("${0}:${0}", CUSTOMER_HEADING_ROW);
// Margins
ps.SetNarrowMargins();
ps.TopMargin = 0.5;
ps.BottomMargin = 0.5;
ps.LeftMargin = 0.5;
ps.RightMargin = 0.5;
ps.HeaderMargin = 0.5;
ps.FooterMargin = 0.5;
// Orientation
ps.Orientation = OrientationValues.Landscape;
// Zoom
//psByCust.ZoomScale = what should this be? Is not a boolean...
// FitToPagesWide
//psByCust.FitToWidth = ; "cannot be assigned to" so how can I set this?
// FitToPagesTall
//psByCust.FitToHeight = 100; "cannot be assigned to" so how can I set this?
I'm not sure about many of these, though, especially the replacement code for "PrintTitleRows" ("PrintHeadings" and "SetCenterHeaderText"), but one thing seems to be totally missing from Spreadsheet Light, namely "PrintArea".
Also, what should the "Zoom" value be? And what corresponds to "FitToPagesWide" and "FitToPagesTall"?
What is the analagous way to accomplish the same thing with Spreadsheet Light? Or does Spreadsheet Light just automatically determine the range to print based on non-empty cells?
I can help with some of these. First up, Print Area.
As Vincent says: Rule 1: Everything begins and ends with SLDocument
SLDocument myWorkbook = new SLDocument();
myWorkbook.SetPrintArea("A1", "E10");
// or
myWorkbook.SetPrintArea(1, 1, 10, 5);
Next: Fit to Pages:
SLPageSettings settings = new SLPageSettings();
settings.ScalePage(2, 3) // print 2 pages wide and 3 long
// There is no info on how to just scale in one dimension, I would use
// a definitely too big™ number in the field you don't care about
// Eg for fit all columns on one page:
settings.ScalePage(1, 99999);
Zoom is a view (not print) thing AFAIK and can be changed between 10 and 400 to set the Zoom percentage - equivalent to Ctrl-scrolling when viewing a spreadsheet.
PrintHeadings displays the row (1, 2, 3, ...) and column headings (A, B, C, ...) when you print, so you can see the value in say, D25 easier.
For printing titles, you use the Set<position>HeaderText in SLPageSettings:
settings.SetCenterHeaderText("My Workbook Title");
Similarly SetLeftHeaderText and SetRightHeaderText
I don't know how to set 'RowsToRepeatAtTop' and 'ColumnsToRepeatAtLeft' which would match Interop's PrintTitleRows.
ProTip: The chm help file that comes with SpreadsheetLight is very useful.
I'm copying and pasting a table using the following code:
Word.Table tableTemplate = document.Tables[tableNumber];
tableTemplate.Select();
word.Selection.Copy(); //word is my Word.Application
word.Selection.MoveDown(Word.WdUnits.wdLine, 2);
word.Selection.PasteAndFormat(Word.WdRecoveryType.wdTableOriginalFormatting);
table = document.Tables[tableNumber + 1];
Unfortunately, the document.Tables.Count variable isn't incremented when the table is pasted, and the last line throws an index out of bounds error. I'm sure it's something minor I'm missing.
In case anyone having a similar problem is looking for a solution, I placed a bookmark below the table, moved the selection cursor there, then selected the range just before the bookmark and pasted.
Word.Bookmark bkmrk = document.Bookmarks["MyBkmrk"];
Word.Range rng = document.Range(bkmrk.Range.Start - 1, bkmrk.Range.Start - 1);
rng.Select();
word.Selection.Paste();
This seemed to work infinitely better than trying to use MoveDown. I'd even tried using MoveDown in the selection by using the number of paragraphs in the range to determine how far, and that entirely didn't work.
Edit:
So, my real issue was that I needed to copy a table and paste some number of them in a loop, then edit the contents of the table. I kept running into the table pasting into itself and just generally being messed up. For anyone who needs to do something similar, here's some help:
Word.Table table = document.Tables[tableNumber];
table.Select();
wordApplication.Selection.Copy();
for(int i = 0; i < tablesINeed; i++)
{
Word.Range rng = document.Range(document.Tables[tableNumber + i].Range.End + 1, document.Tables[tableNumber + i].Range.End + 1);
rng.Select();
wordApplication.Selection.Paste();
// Modify table accordingly
}
It looks simple, but it took a lot of trial and error. Hopefully it will help someone.
I have an answer based on cboler's. I had problems if there is already something behind the table to be copied.
private static List<Table> CloneTables(Application Application, Document doc, int tableNumber, int tablesINeed)
{
List<Table> sameTables = new List<Table>();
Table lastTable = doc.Tables[tableNumber];
sameTables.Add(lastTable);
lastTable.Select();
Application.Selection.Copy();
for (int i = 0; i < tablesINeed; i++)
{
lastTable.Range.Next().InsertParagraphAfter();
Range rng = doc.Range(doc.Tables[tableNumber + i].Range.End + 1, doc.Tables[tableNumber + i].Range.End + 1);
rng.Select();
Application.Selection.Paste();
lastTable = doc.Tables[tableNumber + i + 1];
sameTables.Add(lastTable);
}
return sameTables;
}
I'm trying to obtain the text shown in a MS Word window in C# using Microsoft.Office.Interop.Word.
Please note it's not the whole document or even the page; just the same content the user sees.
The following code seems to work with simple documents:
Application word = new Application();
word.Visible = true;
object fileName = #"example.docx";
word.Documents.Add(ref fileName, Type.Missing, Type.Missing, true);
Rect rect = AutomationElement.FocusedElement.Current.BoundingRectangle;
Range r1 = word.ActiveWindow.RangeFromPoint((int)rect.Left, (int)rect.Top);
Range r2 = word.ActiveWindow.RangeFromPoint((int)rect.Left + (int)rect.Width, (int)rect.Top + (int)rect.Height);
r1.End = r2.Start;
Console.WriteLine(r1.Text.Replace("\r", "\r\n"));
However, when the document includes other structures such as headers, only parts of the text are returned.
So, what's the correct way to achieve this?
Thanks a lot!
Updated Code
Rect rect = AutomationElement.FocusedElement.Current.BoundingRectangle;
foreach (Range r in word.ActiveDocument.StoryRanges) {
int left = 0, top = 0, width = 0, height = 0;
try {
try {
word.ActiveWindow.GetPoint(out left, out top, out width, out height, r);
} catch {
left = (int)rect.Left;
top = (int)rect.Top;
width = (int)rect.Width;
height = (int)rect.Height;
}
Rect newRect = new Rect(left, top, width, height);
Rect inter;
if ((inter = Rect.Intersect(rect, newRect)) != Rect.Empty) {
Range r1 = word.ActiveWindow.RangeFromPoint((int)inter.Left, (int)inter.Top);
Range r2 = word.ActiveWindow.RangeFromPoint((int)inter.Right, (int)inter.Bottom);
r.SetRange(r1.Start, r2.Start);
Console.WriteLine(r.Text.Replace("\r", "\r\n"));
}
} catch { }
}
There may be some problems with this:
Its not reliable. Are you truly able to get consistent results each
time? For example, on a simple "=rand()" document, run the program 5
times in a row without changing the state of Word. When I do this, I
get a different range printed to the console each time. I would first start here: there seems to be something wrong with your logic for getting the ranges. For example, rect.Left keeps returning different numbers every time I execute it against the same document left alone on screen
It gets tricky with other stories. Perhaps RangeFromPoint cannot
extend across multiple story boundaries. However, lets assume it does. You would still need to enumerate each story e.g.
enumerator = r1.StoryRanges.GetEnumerator();
{
while (enumerator.MoveNext()
{
Range current = (Range) enumerator.Current;
}
}
Have you tried to look at How to programmatically extract the text of the currently viewed page of an Office.Interop.Word.Document object ?
You are probably seeing the side effects of range selecting across page elements.
In most cases, if you move your cursor to the top left of the screen, down to the bottom right of the screen it will only select the main body text (no headers or footers). Also, if the document has columns, and those columns start or end off screen, then when you select from the fist column the text through to the last column will be selected, even if it is off the screen.
To my knowledge there is no easy way to achieve your goal unless you are willing to ignore the inconsistencies, or want to deal with all the use cases specifically (images, columns, tables, etc.).
If you can tell us what you are trying to do then we can offer alternatives, otherwise please mark an answer as correct.
The above discussion is very specific to the Office versions.
I think my code will work in all cases.
IntPtr h = (IntPtr)Globals.ThisAddIn.Application.ActiveWindow.Hwnd;
String strText = NativeInvoker.GetWindowText(h);
if (strText != null && strText.StartsWith(Globals.ThisAddIn.Application.ActiveWindow.Caption))
{
h = NativeInvoker.FindWindowEx(h, IntPtr.Zero, "_WwF", "");
h = NativeInvoker.FindWindowEx(h, IntPtr.Zero, "_WwB", null);
h = NativeInvoker.FindWindowEx(h, IntPtr.Zero, "_WwG", null);
Rect t;
if (NativeInvoker.GetWindowRect(h, out t))
{
Range r1 = (Range)Globals.ThisAddIn.Application.ActiveWindow.RangeFromPoint((int)t.Left, (int)t.Top);
Range r2 = (Range)Globals.ThisAddIn.Application.ActiveWindow.RangeFromPoint((int)t.Right, (int)t.Bottom);
Range r = Globals.ThisAddIn.Application.ActiveDocument.Range(r1.Start, r2.Start);
....
You can refer to the NativeInvoker class contents from anyware.
I hope my code will help your work.
Phon.
I have similar requirement in my Word add ins.
Try bellow code, it works for me.
IntPtr h = Process.GetCurrentProcess().MainWindowHandle;
h = NativeMethodsActiveScreen.FindWindowExW(h, new IntPtr(0), "_WwF", "");
h = NativeMethodsActiveScreen.FindWindowExW(h, new IntPtr(0), "_WwB", null);
h = NativeMethodsActiveScreen.FindWindowExW(h, new IntPtr(0), "_WwG", null);
NativeMethodsActiveScreen.tagRECT t = new NativeMethodsActiveScreen.tagRECT();
NativeMethodsActiveScreen.GetWindowRect(h, out t);
var Aw = RibbonHelper.SharedApplicationInstance.ActiveWindow;
Range fullDocRange = RibbonHelper.SharedApplicationInstance.ActiveDocument.Range();
Range r1 = RibbonHelper.SharedApplicationInstance.ActiveWindow.RangeFromPoint(t.left, t.top);
Range r2 = RibbonHelper.SharedApplicationInstance.ActiveWindow.RangeFromPoint(t.right, t.bottom);
Range r = RibbonHelper.SharedApplicationInstance.ActiveDocument.Range(r1.Start, r2.Start);
if it helps please mark answer as helpful.
Thanks