Chris M. Darby
Вот несколько примеров кода C# с несколькими демонстрациями использования интерактивных слов, включая один подход к выборочной установке отдельных слов жирным шрифтом. Хитрость заключается в том, чтобы свернуть диапазон между каждым изменением или отклонением с помощью стилей слов и типов объектов Word.
using System;
using Word = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
namespace WordDemo {
public class WordDemo {
string wordFile;
Word.Application wordApp;
Word.Document wordDoc;
Word.Range range;
public WordDemo() {
// Set your filename here; defaults to saving to your desktop
wordFile = SetFileDetails("WordCreationTest.docx");
InitializeWordObjects();
AddTextToWord();
AddTableToWord();
SaveCloseQuitWord();
}
private string SetFileDetails(string filename) {
string userDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
return userDesktop + "\\" + filename;
}
private void InitializeWordObjects() {
wordApp = new Word.Application();
wordApp.Visible = true;
wordDoc = new Word.Document();
wordDoc = wordApp.Documents.Add();
range = wordDoc.Range();
}
private void AddTextToWord() {
range.InsertAfter("Testing 1, 2, 3");
range.InsertParagraphAfter();
range.InsertParagraphAfter();
range.InsertAfter(
"Adding a collection of text to the document here, some " +
"really incredibly interesting stuff to read, I'm sure... " +
"or at least that's the rumor. Also, "
);
range.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
range.InsertAfter("these words");
// Interop doesn't recognize C# booleans, so we convert to integers:
range.Font.Bold = Convert.ToInt32(true);
range.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
range.InsertAfter(" are bold.");
range.Font.Bold = Convert.ToInt32(false);
range.InsertParagraphAfter();
range.InsertParagraphAfter();
}
private void AddTableToWord() {
range.InsertAfter(
"Okay, well, that was interesting. Next, here is a table creation " +
"demonstration. This table is comprised of 3 rows and 4 columns, " +
"defaulting to autofit, and setting the inside and outside " +
"line styles to single line style."
);
range.InsertParagraphAfter();
range.InsertParagraphAfter();
range.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
Word.Table table = wordDoc.Tables.Add(
range, 3, 4,
Word.WdDefaultTableBehavior.wdWord9TableBehavior
);
table.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
table.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
range = wordDoc.Content;
range.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
range.InsertParagraphAfter();
}
private void SaveCloseQuitWord() {
wordDoc.SaveAs2(wordFile);
wordDoc.Close();
Marshal.FinalReleaseComObject(wordDoc);
wordApp.Quit();
Marshal.FinalReleaseComObject(wordApp);
}
}
}