|
如何用程式實現word查找替換方法,現有方法出現”OfficeTools字串參數太長”錯誤訊息? |
|
|
查找替換功能有字元數的限制,替換的最大長度為255個字元,應該直接修改Word中的Sentences或者Words對象來實現,如: OpenFileDialog dialog = new OpenFileDialog(); if (dialog.ShowDialog() == DialogResult.OK) { StreamReader reader = new StreamReader(dialog.FileName, Encoding.UTF8); string text = reader.ReadToEnd(); reader.Close();
Word.Application objWord = new Word.Application(); if (objWord == null) { throw new Exception("Word could not be started. Check that your office installation and project references are correct"); }
objWord.Visible = true; objWord.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; object objMiss = Missing.Value; Word.Document objDocument = objWord.Documents.Add(ref objMiss, ref objMiss, ref objMiss, ref objMiss); try { objDocument.Sentences[1].Text = text; object filename = dialog.FileName + ".doc"; objDocument.SaveAs(ref filename, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss); } finally { ((Word._Application)objWord).Quit(ref objMiss, ref objMiss, ref objMiss); Marshal.ReleaseComObject(objDocument); Marshal.ReleaseComObject(objWord); objDocument = null; objWord = null; objMiss = null; GC.Collect(); } }
|
|
|