Introduction
About a week ago, I submitted an article about a summary of C# control Excel skills. This article will show you a summary of basic skills on C# controlling Word. Wish this summary is useful for all of you.
1. Insert Text or Image into Designated Bookmark
using Word = Microsoft.Office.Interop.Word;
object Nothing = System.Reflection.Missing.Value;
object format = Word.WdSaveFormat.wdFormatDocument;
Word.Application wordApp = new Word.ApplicationClass();
object srcFileName = @"c:\new1.doc"; Word.Document wordDoc2 = wordApp.Documents.Open
(ref srcFileName, ref format, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing);
try
{
object bookmarkName = "jlr";
wordDoc2.Bookmarks.get_Item(ref bookmarkName).Select();
wordApp.Selection.InlineShapes.AddPicture
("c:\\1.jpg", ref Nothing, ref Nothing, ref Nothing);
wordDoc2.Save();
}
catch { }
finally
{
wordDoc2.Close(ref Nothing, ref Nothing, ref Nothing);
if (wordDoc2 != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc2);
wordDoc2 = null;
}
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
if (wordApp != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
wordApp = null;
}
}
GC.Collect();
2. Replace Bookmark Content in Word Template
object omissing = system.reflection.missing.value;
word.applicationclass wordapp= new microsoft.office.interop.word.applicationclass();
object readonly = false;
object template = templatepath;
word._document doc = wordapp.documents.open(ref template, ref omissing,ref readonly,
ref omissing, ref omissing, ref omissing, ref omissing, ref omissing, ref omissing,
ref omissing, ref omissing, ref omissing,
ref omissing,ref omissing,ref omissing,ref omissing);
for (int i = 1; i <= doc.bookmarks.count; i++)
{
object j = i;
word.range wordrng = doc.bookmarks.get_item(ref j).range;
wordrng.text = "This is the" + i + "bookmark, name as" +
doc.bookmarks.get_item(ref j).name;
}
object savefilename = mappath(request.applicationpath + "/document") +
"/" + guid.newguid().tostring() + ".doc";
doc.saveas(ref savefilename,ref omissing,ref omissing,ref omissing,
ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,
ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,
ref omissing,ref omissing);
doc.close( ref omissing, ref omissing, ref omissing );
wordapp.quit( ref omissing, ref omissing, ref omissing );
3. Search Text in Word
object filename=""; string strKey=""; object MissingValue=Type.Missing;
Word.Application wp=new Word.ApplicationClass();
Word.Document wd=wp.Documents.Open(ref filename,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue);
int i=0,iCount=0;
Word.Find wfnd;
if (wd.Paragraphs!=null && wd.Paragraphs.Count>0)
{
iCount=wd.Paragraphs.Count;
for(i=1;i<=iCount;i++)
{
wfnd=wd.Paragraphs[i].Range.Find;
wfnd.ClearFormatting();
wfnd.Text=strKey;
if (wfnd.Execute(ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue))
{
MessageBox.Show("include designated keyword!",
"search result",MessageBoxButtons.OK);
break;
}
}
}
4. C# Dynamic Generate Word File and Fill in with Data
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Word;
namespace CreateWordFile
{
class Program
{
static void Main(string[] args)
{
CreateWordFile("");
}
public static string CreateWordFile(string CheckedInfo)
{
string message = "";
try
{
Object Nothing = System.Reflection.Missing.Value;
Directory.CreateDirectory("C:/CNSI"); string name = "CNSI_" + "53asdf" + ".doc";
object filename = "C://CNSI//" + name; Word.Application WordApp = new Word.ApplicationClass();
Word.Document WordDoc = WordApp.Documents.Add
(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[页眉内容]");
WordApp.Selection.ParagraphFormat.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphRight; WordApp.ActiveWindow.View.SeekView =
WdSeekView.wdSeekMainDocument;
WordApp.Selection.ParagraphFormat.LineSpacing = 15f;
object count = 14;
object WdLine = Word.WdUnits.wdLine; WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing); WordApp.Selection.TypeParagraph();
Word.Table newTable = WordDoc.Tables.Add
(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing);
newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap;
newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
newTable.Columns[1].Width = 100f;
newTable.Columns[2].Width = 220f;
newTable.Columns[3].Width = 105f;
newTable.Cell(1, 1).Range.Text = "Product information table";
newTable.Cell(1, 1).Range.Bold = 2; newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
WordApp.Selection.Cells.VerticalAlignment =
Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; WordApp.Selection.ParagraphFormat.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphCenter;
newTable.Cell(2, 1).Range.Text = " Product information table ";
newTable.Cell(2, 1).Range.Font.Color =
Word.WdColor.wdColorDarkBlue; newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
WordApp.Selection.Cells.VerticalAlignment =
Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
newTable.Cell(3, 1).Range.Text = "Brandname";
newTable.Cell(3, 2).Range.Text = "BrandName";
newTable.Cell(3, 3).Select(); object moveUnit = Word.WdUnits.wdLine;
object moveCount = 5;
object moveExtend = Word.WdMovementType.wdExtend;
WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
WordApp.Selection.Cells.Merge();
string FileName = "c:\\Winter.jpg"; object LinkToFile = false;
object SaveWithDocument = true;
object Anchor = WordDoc.Application.Selection.Range;
WordDoc.Application.ActiveDocument.InlineShapes.AddPicture
(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f; WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f; Word.Shape s =
WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
s.WrapFormat.Type = Word.WdWrapType.wdWrapSquare;
newTable.Cell(12, 1).Range.Text = "product special attribute";
newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
WordDoc.Content.Tables[1].Rows.Add(ref Nothing);
WordDoc.Paragraphs.Last.Range.Text = "Created date:" +
DateTime.Now.ToString(); WordDoc.Paragraphs.Last.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphRight;
WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
message = name + " File created successful, save to C:CNSI";
}
catch
{
message = "File export error!";
}
Console.WriteLine(message);
return message;
}
5. C# Convert Word, Excel to HTML
Microsoft.Office.Interop.Word.ApplicationClass appclass =
new Microsoft.Office.Interop.Word.ApplicationClass(); Type wordtype = appclass.GetType();
Microsoft.Office.Interop.Word.Documents docs = appclass.Documents;
Type docstype = docs.GetType();
object filename = ; Microsoft.Office.Interop.Word.Document doc =
(Microsoft.Office.Interop.Word.Document)docstype.InvokeMember
("Open",System.Reflection.BindingFlags.InvokeMethod,null,docs,
new object {filename,true,true}); Type doctype = doc.GetType();
object savefilename = <a href="mailto:Application.StartupPath+@%22\ccyt_chm\inform\%22+n.FullPath.Split('.').GetValue(0)+%22.html%22;doctype.InvokeMember(%22SaveAs%22,System.Reflection.BindingFlags.InvokeMethod,null,doc,new">Application.StartupPath+@"\ccyt_chm\inform\"+
n.FullPath.Split('.').GetValue(0)+".html";
doctype.InvokeMember("SaveAs",System.Reflection.BindingFlags.InvokeMethod,
null,doc,new</a> object[]{savefilename,
Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML});// Save as Html format
wordtype.InvokeMember
("Quit",System.Reflection.BindingFlags.InvokeMethod,
null,appclass,null);// Exit
Thread.Sleep(3000);// choke 3 seconds for safely exiting
StreamReader objreader = new StreamReader(savefilename.ToString(),
System.Text.Encoding.GetEncoding("GB2312")); // the content below is to
// add the word file download in Html
FileStream fs = new FileStream(savefilename.ToString().Split
('.').GetValue(0).ToString()+"$.html",FileMode.Create);
streamHtmlHelp = new System.IO.StreamWriter
(fs,System.Text.Encoding.GetEncoding("GB2312"));
streamHtmlHelp.WriteLine("<a href="%5C%22%22+n.Text+%22%5C%22">Source file download</a>");
do
{
str = objreader.ReadLine();
streamHtmlHelp.WriteLine(str);
}
while (str != "");
streamHtmlHelp.Close();
objreader.Close();
File.Delete(savefilename.ToString());
File.Move(savefilename.ToString().Split('.').GetValue(0).ToString()+"$.html",
savefilename.ToString());Application.StartupPath+@"\ccyt_chm\inform\"+n.FullPath
//Excel -〉Html
Microsoft.Office.Interop.Excel.Application repExcel =
new Microsoft.Office.Interop.Excel.Application ();//Sample Excel
Microsoft.Office.Interop.Excel.Workbook workbook = null;
Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
workbook = repExcel.Application.Workbooks.Open();//Open file,
//n.FullPathis the file path
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
object htmlFile = Application.StartupPath+@"\ccyt_chm\inform\"+
n.FullPath.Split('.').GetValue(0)+".html";
object ofmt = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
workbook.SaveAs(htmlFile,ofmt,Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);//save as
object osave = false;
workbook.Close(osave,Type.Missing,Type.Missing);// close objects one by one
repExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
worksheet = null;
GC.Collect();// recycle
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook=null;
GC.Collect();
System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel.Application.Workbooks);
GC.Collect();
System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel);
repExcel = null;
GC.Collect();
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName
("EXCEL");// close process according to the time
foreach ( System.Diagnostics.Process p in process)
{
if (DateTime.Now.Second - p.StartTime.Second > 0 &&
DateTime.Now.Second - p.StartTime.Second < 5)
{
p.Kill();
}
}
Thread.Sleep(3000);// guarantee completely shut download
StreamReader objreader = new StreamReader(htmlFile.ToString().Split('.').GetValue(0)+
".files\\sheet001.html",System.Text.Encoding.GetEncoding
("GB2312")); // The content below is to add an original excel download
//hyperlink in the first Excel frame.
FileStream fs = new FileStream(htmlFile.ToString().Split('.').GetValue
(0)+".files\\sheet001$.html",FileMode.Create);
streamHtmlHelp = new System.IO.StreamWriter
(fs,System.Text.Encoding.GetEncoding("GB2312"));
streamHtmlHelp.WriteLine("<a href="%5C%22%22+%22../%22+n.Text+%22%5C%22">
Source code download</a>
");
do
{
str = objreader.ReadLine();
streamHtmlHelp.WriteLine(str);
}
while (str != "");
streamHtmlHelp.Close();
objreader.Close();
File.Delete(htmlFile.ToString().Split('.').GetValue(0)+".files\\sheet001.html");
File.Move(htmlFile.ToString().Split('.').GetValue(0)+
".files\\sheet001$.html",htmlFile.ToString().Split('.').GetValue(0)+
".files\\sheet001.html");Application.StartupPath+@"\ccyt_chm\inform\"+
n.FullPath,Type.Missing,Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing
6. Connect Word and Excel with MailMerge Function
using Word = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Diagnostics;
using System.IO;
Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
object missing = System.Reflection.Missing.Value;
object falseValue = false;
object trueValue = true;
private void button1_Click(object sender, EventArgs e)
{
object fileName = CopyTemplateDoc(); Word.Document doc = WordApp.Documents.Open
(ref fileName, ref missing, ref falseValue, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref trueValue,
ref missing, ref missing, ref missing);
object linkTo = CopyExcelData(); object query = "SELECT * FROM `Sheet1$`"; object header = "Name,Category,Address,Content";
try
{
doc.MailMerge.CreateDataSource(ref linkTo, ref missing,
ref missing, ref header, ref falseValue, ref query,
ref missing, ref missing, ref trueValue);
doc.MailMerge.Fields.Add(WordApp.Selection.Range, "Name"); MessageBox.Show("success");
catch (Exception ex)
MessageBox.Show(ex.Message);
finally
{
doc.Save(); CloseApp(); CopyExcelData(); }
}
public void CloseApp()
{
WordApp.Documents.Close(ref trueValue, ref missing, ref missing);
WordApp.Quit(ref trueValue, ref missing, ref missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);
GC.Collect();
}
7. C# Read Word
Word.Application app =
new Microsoft.Office.Interop.Word.Application(); Word.Document doc = null; public override void openFile(object fileName){} public override object readPar(int i){} public override int getParCount(){} public override void closeFile(){} public override void quit(){}
public void replaceChar(){}
public override void openFile(object fileName)
{
try
{
if (app.Documents.Count > 0)
{
if (MessageBox.Show("Already open a Word file,
Do you want to close and reopen the file?", "reminder",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
object unknow = Type.Missing;
doc = app.ActiveDocument;
if (MessageBox.Show("Do you want to save?",
"Save", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
app.ActiveDocument.Save();
}
app.ActiveDocument.Close(ref unknow, ref unknow, ref unknow);
app.Visible = false;
}
else
{
return;
}
}
}
catch (Exception)
{
app = new Microsoft.Office.Interop.Word.Application();
}
try
{
object unknow = Type.Missing;
app.Visible = true;
doc = app.Documents.Open(ref fileName,
ref unknow, ref unknow, ref unknow,
ref unknow, ref unknow,
ref unknow, ref unknow, ref unknow,
ref unknow, ref unknow,
ref unknow, ref unknow, ref unknow,
ref unknow, ref unknow);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.ToString());
}
}
public override object readPar(int i)
{
try
{
string temp = doc.Paragraphs[i].Range.Text.Trim();
return temp;
}
catch (Exception e) {
MessageBox.Show("Error:"+e.ToString());
return null;
}
}
public override int getParCount()
{
return doc.Paragraphs.Count;
}
public override void closeFile()
{
try
{
object unknow = Type.Missing;
object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
app.ActiveDocument.Close(ref saveChanges, ref unknow, ref unknow);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.ToString());
}
}
public override void quit()
{
try
{
object unknow = Type.Missing;
object saveChanges = Word.WdSaveOptions.wdSaveChanges;
app.Quit(ref saveChanges, ref unknow, ref unknow);
}
catch (Exception)
{
}
}
public void replaceChar() {
try
{
object replaceAll = Word.WdReplace.wdReplaceAll;
object missing = Type.Missing;
app.Selection.Find.ClearFormatting();
app.Selection.Find.Text = "^l";
app.Selection.Find.Replacement.ClearFormatting();
app.Selection.Find.Replacement.Text = "^p";
app.Selection.Find.Execute(
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref replaceAll, ref missing, ref missing, ref missing, ref missing);
}
catch (Exception e)
{
MessageBox.Show("Error, please do it again");
}
}
8. C# Open Word File and Display Content
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog opd = new OpenFileDialog();
opd.InitialDirectory = "c:\\";
opd.Filter = "Word文档(*.doc)|*.doc|Text(*.txt)|*.txt|RTF File(*.rtf)|
*.rtf|All files(*.*)|*.*";
opd.FilterIndex = 1;
if (opd.ShowDialog() == DialogResult.OK && opd.FileName.Length > 0)
{
// Create Word class sample
Word.ApplicationClass app = new Word.ApplicationClass();
Word.Document doc = null;
object missing = System.Reflection.Missing.Value;
object FileName = opd.FileName;
object readOnly = false;
object isVisible = true;
object index = 0;
try
{
doc = app.Documents.Open(ref FileName, ref missing, ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref isVisible, ref missing,
ref missing, ref missing, ref missing);
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
// Get data from clipboard
IDataObject data=Clipboard.GetDataObject();
this.richTextBox1.Text=data.GetData(DataFormats.Text).ToString();
}
finally
{
if (doc != null)
{
doc.Close(ref missing, ref missing, ref missing);
doc = null;
}
if (app != null)
{
app.Quit(ref missing, ref missing, ref missing);
app = null;
}
}
}
}
I welcome any kind of feedback from all of you!