Summarize C# Control Word Skills
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# controllong 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(); //open website and choose content object srcFileName = @"c:\new1.doc"; // images inside 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"; //Word.Range rng = wordDoc2.Bookmarks.get_Item(ref bookmarkName).Range; //rng.Text = "newText"; //object range = rng; //wordDoc2.Bookmarks.Add("jlr", ref range); wordDoc2.Bookmarks.get_Item(ref bookmarkName).Select(); wordApp.Selection.InlineShapes.AddPicture("c:\\1.jpg", ref Nothing, ref Nothing, ref Nothing); wordDoc2.Save(); } catch { } finally { // Close website wordDoc2 wordDoc2.Close(ref Nothing, ref Nothing, ref Nothing); if (wordDoc2 != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc2); wordDoc2 = null; } // close wordApp 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
// open 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); // modify 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; } // save 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=""; // file path string strKey=""; // text which you want o search 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(""); } // The example below includes C# create Word, insert table and set up style: // Our point is to introduce some methods of C# control Word file. So some involved information was omitted. public static string CreateWordFile(string CheckedInfo) { string message = ""; try { Object Nothing = System.Reflection.Missing.Value; Directory.CreateDirectory("C:/CNSI"); // Create file category string name = "CNSI_" + "53asdf" + ".doc"; object filename = "C://CNSI//" + name; // file save path // create Word file Word.Application WordApp = new Word.ApplicationClass(); Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); // Add header WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView; WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader; WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[页眉内容]"); WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;// Set right alignment WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;// set pop up header WordApp.Selection.ParagraphFormat.LineSpacing = 15f;// Set file line spacing // Move focus and newline object count = 14; object WdLine = Word.WdUnits.wdLine;//newline; WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//move focus WordApp.Selection.TypeParagraph();// insert paragraph // Create table in Word file Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing); // Set table style 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; // Fill in table newTable.Cell(1, 1).Range.Text = "Product information table"; newTable.Cell(1, 1).Range.Bold = 2;// Set text font as bold in Cells // Merge cells newTable.Cell(1, 1).Merge(newTable.Cell(1, 3)); WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;// Center Vertically WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;// Center Horizontal // Fill in table newTable.Cell(2, 1).Range.Text = " Product information table "; newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;// Set text color in Cells //Merge Cells newTable.Cell(2, 1).Merge(newTable.Cell(2, 3)); WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; // Fill in table newTable.Cell(3, 1).Range.Text = "Brandname"; newTable.Cell(3, 2).Range.Text = "BrandName"; // merge cells longitudinal newTable.Cell(3, 3).Select();// choose a row 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(); // insert image string FileName = "c:\\Winter.jpg";// image path 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;//image width WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//image height // Set image layout as Square 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)); // Add rows in table WordDoc.Content.Tables[1].Rows.Add(ref Nothing); WordDoc.Paragraphs.Last.Range.Text = "Created date:" + DateTime.Now.ToString();//“Alignment” WordDoc.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; // Save file 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
//Word -〉Html Microsoft.Office.Interop.Word.ApplicationClass appclass = new Microsoft.Office.Interop.Word.ApplicationClass();//Sample Word Type wordtype = appclass.GetType(); Microsoft.Office.Interop.Word.Documents docs = appclass.Documents; //Get Document Type docstype = docs.GetType(); object filename = ;//n.FullPath is Word file path 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});// Open file Type doctype = doc.GetType(); object savefilename = Application.StartupPath+@"\ccyt_chm\inform\"+n.FullPath.Split('.').GetValue(0)+".html"; doctype.InvokeMember("SaveAs",System.Reflection.BindingFlags.InvokeMethod,null,doc,new 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
// Purpose: Use Word MailMerge function, Data source is in Excel file. //About Word MailMerge function // Word provides email template, you can choose different data source such as database, excel, etc. // To realize this function, the program should do: //1, Open Word file object //2, Set MailMerge Data Source: Designate Excel, Designate queries,Designate connected column //3, Close/save //reference using Word = Microsoft.Office.Interop.Word; using System.Reflection; using System.Diagnostics; using System.IO; //variables: Word COM object need imported reference define Word.Application WordApp = new Microsoft.Office.Interop.Word.Application(); object missing = System.Reflection.Missing.Value; object falseValue = false; object trueValue = true; // dispose // Note: //1:the way to open Word file //2:Write query //3:Set column, after set, columns will be shown in Word file //4: After close Word, cope Excel will lead to a large size Excel file and which may not available to be opened. private void button1_Click(object sender, EventArgs e) { object fileName = CopyTemplateDoc();//copy doc in 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();//copy excel data object query = "SELECT * FROM `Sheet1$`";//data from sheet1 object header = "Name,Category,Address,Content";//filed list 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");//add one filed to test MessageBox.Show("success"); catch (Exception ex) MessageBox.Show(ex.Message); finally { doc.Save();//save word CloseApp();//close word app CopyExcelData();//copy data again,******************* } } // Close Word object 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(); //this.KillExcelProcess(); }
7. C# Read Word
//1: // Refer to,Microsoft Word 11.0 Object //Library //2: //Add using Word = Microsoft.Office.Interop.Word; //3: //Add in program Word.Application app = new Microsoft.Office.Interop.Word.Application(); // permit open Word process Word.Document doc = null; // Record file opened by Word // Word file is not Word process 4: // usually, there are only a few methods to extract word content public override void openFile(object fileName){} //Open file public override object readPar(int i){} // Read Word file, paragraph i public override int getParCount(){} // Back to Word file paragraph public override void closeFile(){} // Close file public override void quit(){} //Close Word process public void replaceChar(){} 5: Code 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) { //MessageBox.Show("You might close file"); 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) { //Invoke and open file dialog to get Word, RTF, text file path name 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; } } } }
推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架