Insert formatted text to Word document - c#

I insert text to a Word document. This is done by selection.TypeText("text");
I would like to insert formatted text to a Word document, something like:
public override void InsertText(string content, string format)
{
selection.Style = format; //something like this
selection.Font.Name = "Heading 1"; //or like this
selection.TypeText(content);
}
Any ideas?

For a Word Document-Level Customization where Microsoft.Office.Interop.Word is referenced, this works:
this.ActiveWindow.Selection.Range.Font.Name = "Arial";
this.ActiveWindow.Selection.Range.Font.Size = 36;
You can also assign the range of a selection to a range variable and then apply formats to the variable as in:
Word.Range myRange = this.ActiveWindow.Selection.Range;
myRange.Font.Size = 18;
myRange.Font.Name = "Arial";
EDIT (Response to OP's question in comments)
To apply a Heading style to the selected text assign one of Word's WdBuiltinStyle enumeration members:
object headingStyle = Word.WdBuiltinStyle.wdStyleHeading1;
this.ActiveWindow.Selection.Range.set_Style(ref headingStyle);
To view the full list of enumeration members, see this:
MSDN: WdBuiltinStyle enumeration

Related

NPOI doesn't apply format to .xls

C#, NPOI
Good evening, i'm trying to fill in an empty template with values(numbers, but in string variable), that needs to be in cells.
So, when it came to formatting, i've stuck with styling. That means, when i wrote the value inside(in pre-formatted cell) i get just the string value, that was in array.
But, when i open file, click "edit cell", then apply without any changes, then cell is formatted, with the format, which was in a template
I tried to apply previous style in cell(basically just copy style in var, before setting a value, then re-apply style), but, it didnt help.
Here is the video of my doings
var cr = new CellReference(cellAndValue[i, 0]);
var row = sheet?.GetRow(cr.Row);
var cell = row?.GetCell(cr.Col);
var prevtype = cell.CellType;
var prevstyle = cell.CellStyle;
var dataformat = cell.CellStyle.DataFormat;
CellType type = cell.CellType;
cell.SetCellValue(cellAndValue[i, 0]);
How to resolve that?)
It was required to convert incoming data to int, before inserting it XD
int n;
if (Int32.TryParse(cellAndValue[i, 1], out n))
{
cell.SetCellValue(n);
}
else
{
cell.SetCellValue(cellAndValue[i, 1]);
}

Keep excel cell format as text with "date like" data

This seems silly, but I haven't been able to get my values in the format of #/#### to write as the literal string rather than becoming formatted as a date within excel.
I'm using ClosedXML to write to excel, and using the following:
// snip
IXLRangeRow tableRow = tableRowRange.Row(1);
tableRow.Cell(1).DataType = XLCellValues.Text;
tableRow.Cell(1).Value = "2/1997";
// snip
Looking at the output excel sheet I get in the cell 2/1/1997 - even though I'm setting the format as text in code, I'm getting it as a "Date" in the excel sheet - I checked this by right clicking the cell, format cell, seeing "date" as the format.
If I change things up to:
// snip
IXLRangeRow tableRow = tableRowRange.Row(1);
tableRow.Cell(1).Value = "2/1997";
tableRow.Cell(1).DataType = XLCellValues.Text;
// snip
I instead get 35462 as my output.
I just want my literal value of 2/1997 to be displayed on the worksheet. Please advise on how to correct.
try this
ws.Cell(rowCounter, colCounter).SetValue<string>(Convert.ToString(fieldValue));
Not sure about from ClosedXML, but maybe try Range.NumberFormat (MSDN Link)
For example...
Range("A1").NumberFormat = "#"
Or
Selection.NumberFormat = "#/####"
Consider:
tableRow.Cell(1).Value = "'2/1997";
Note the single quote.
ws.Cell(rowCounter, colCounter).Value="'"+Convert.ToString(fieldValue));
Formatting has to be done before you write values to the cells.
I had following mechanism, run after I make worksheet, right before I save it:
private void SetColumnFormatToText(IXLWorksheet worksheet)
{
var wholeSheet = worksheet.Range(FirstDataRowIndexInExcel, StartCellIndex, RowCount, HeaderCount);
wholeSheet.Style.NumberFormat.Format = "#";
}
which didn't do squat.
Doing it before I write values to the cells in a row did it.
worksheet.Range(RowIndex, StartCellIndex, RowIndex, EndCellIndex).Style.NumberFormat.Format = "#";
with cell value assignments following immediately after.

Add hyperlink to paragraph using word Interop

I'm trying to add an hyperlink to some XML being inserted in a field of a Word Document (using Microsoft.Office.Interop.Word).
The XML being inserted contains multiple paragraphs, each containing some text that should be converted to a hyperlink. The text that contains the hyperlink is extracted from the end of the paragraph after the "Available at " substring is found.
The following code is able to create the hyperlink but the first hyperlink is always applied to all paragraphs. I was expecting the code to create an hyperlink for each of the paragraphs being iterated.
My guess is that the paragraph.Range object is pointing to text that is in fact the whole XML inserted as opposed to the text contained within the paragraph. I've also confirmed that the paragraph.Range.Text property returns the correct text for each paragraph so I am completely confused as to what should be expected for the Range property.
Any ideas? Thanks in advance.
if (!string.IsNullOrWhiteSpace(bibliography))
{
const string linkToken = "Available at ";
field.Result.InsertXML(bibliography);
foreach (Paragraph paragraph in field.Result.Paragraphs)
{
var paragraphText = paragraph.Range.Text;
var indexOfLink = paragraphText.IndexOf(linkToken, StringComparison.OrdinalIgnoreCase);
if (indexOfLink >= 0)
{
var linkStart = indexOfLink + linkToken.Length;
var linkPart = paragraphText.Substring(linkStart);
Uri uriFound;
if (Uri.TryCreate(linkPart, UriKind.Absolute, out uriFound))
{
object linkAddress = uriFound.ToString();
paragraph.Range.Hyperlinks.Add(paragraph.Range, ref linkAddress);
}
}
}
}

How to add bookmark in word document header programmatically?

I have done bookmark creation in word document. but, In main text part not in header and footer part. Now, I want to create bookmark in Primary Header Section.
Actually, I am trying to update text of bookmark at run time. But, whenever I change the text of bookmark it get removed. So, I have to create it again programmatically.
This is my code to replace the text of word document bookmark.
if (doc.Bookmarks.Exists(_bookMarkName))
{
object oBookMark = _bookMarkName;
//Getting Bookmark Object
Microsoft.Office.Interop.Word.Bookmark bookmark = doc.Bookmarks.get_Item(ref oBookMark);
//calculating range to create bookmark.
object start = bookmark.Range.Start;
object end = bookmark.Range.Start + _value.Length;
//After replacing this text, bookmark will be removed from the document. So, we have to creat it again.
bookmark.Range.Text = _value;
//Creating range from new values.
object range = doc.Range(ref start, ref end);
doc.Bookmarks.Add(_bookMarkName, ref range); //Adding new bookmark with new range
}
So, what is the problem in this code is the StoryType property of bookmark object will be Microsoft.Office.Interop.Word.WdStoryType.wdPrimaryHeaderStory before replacing bookmark text. but, after creating new bookmark the property StoryType will be taken as Microsoft.Office.Interop.Word.WdStoryType.wdMainTextStory instead of Microsoft.Office.Interop.Word.WdStoryType.wdPrimaryHeaderStory. So, How do I change that property or assign that property when bookmark is being created. The property StoryType is ReadOnly. So, I could not assign it after creating bookmark.
`
The problem is basically creating the new range using the doc as the starting point. SInce the Range object doesn't have a Range method, I think you would have to get the relevant StoryRange from the bookmark's range, then use GetRange to get a range in the appropriate story. I haven't checked...
...because that should not be necessary, assuming that you want the replacement bookmark to "cover" the text that you just inserted, because you should be able to do something more like this, assuming you can retranslate this VBA syntax back into C#
Dim bm As Word.Bookmark
Dim bookMarkName As String
Dim doc As Word.Document
Dim newValue As String
Dim rng As Word.Range
'.
'.
If doc.Bookmarks.Exists(bookMarkName) Then
' Could do the following two statements in one
Set bm = doc.Bookmarks(bookMarkName)
Set rng = bm.Range
rng.Text = newValue
doc.Bookmarks.Add bookMarkName, rng
Set rng = Nothing
Set bm = Nothing
End If

Insert text to Word document

I would like to insert text to Word document, in a specified format, using Interop.Word:
Something like this :
wordDoc.InsertText("Text \n", "Arial");
or
wordDoc.InsertText("Text \n", "Bold");
Is it possible?
There is no direct method like this AFAIK. However, you can write a wrapper over Word Interop and do it. Internally inside your InsertText() method you will have to do the following.
1: Use the Text property of a Range object to insert text in a document.
object start = 0;
object end = 12;
Word.Range rng = this.Range(ref start, ref end);
rng.Text = "New Text";
rng.Select();
2: Format text using a document-level customization.
// Set the Range to the first paragraph.
Word.Range rng = this.Paragraphs[1].Range;
// Change the formatting.
rng.Font.Size = 14;
rng.Font.Name = "Arial";
rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
rng.Select();
For further details please see this and this which I have used sometime back with good results.
Hope this helps.

Categories