我正在尝试通过Interop.Word (11.0)使用Word自动化为Word文档编写查找/替换代码。我的文档都有各种用方括号括起来的字段(不会在Document.Fields中显示),例如,<DATE>
需要用DateTime.Now.Format("MM/dd/yyyy")
替换。查找/替换工作正常。但是,要替换的某些文本是右对齐的,替换后,文本将换行到下一行。有什么方法可以在执行替换时保留对齐方式吗?代码如下:
using Word = Microsoft.Office.Interop.Word;
Word.Application wordApp = null;
try
{
wordApp = new Word.Application {Visible = false};
//.... open the document ....
object unitsStory = Word.WdUnits.wdStory;
object moveType = Word.WdMovementType.wdMove;
wordApp.Selection.HomeKey(ref unitsStory, ref moveType);
wordApp.Selection.Find.ClearFormatting();
wordApp.Selection.Find.Replacement.ClearFormatting(); //tried removing this, no luck
object replaceTextWith = DateTime.Now.ToString("MM/dd/yyyy");
object textToReplace = "<DATE>";
object replaceAll = Word.WdReplace.wdReplaceAll;
object typeMissing = System.Reflection.Missing.Value;
wordApp.Selection.Find.Execute(ref textToReplace, ref typeMissing,
ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing,
ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing,
ref replaceTextWith, ref replaceAll, ref typeMissing, ref typeMissing,
ref typeMissing, ref typeMissing);
// ... save quit etc....
}
finally
{
//clean up wordApp
}
蒂娅。
发布于 2011-02-15 03:21:41
您可以使用Microsoft.Office.Interop.Word.WdParagraphAlignment进行对齐
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
object missing = System.Type.Missing;
try
{
object fileName = @"C:\TT\change.doc";
doc = word.Documents.Open(ref fileName,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
doc.Activate();
foreach (Microsoft.Office.Interop.Word.Range tmpRange in doc.StoryRanges)
{
tmpRange.Find.Text = "<DATE>";
tmpRange.Find.Replacement.Text = DateTime.Now.ToString("MM/dd/yyyy");
tmpRange.Find.Replacement.ParagraphFormat.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;
tmpRange.Find.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;
object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
tmpRange.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);
}
doc.Save();
doc.Close(ref missing, ref missing, ref missing);
word.Application.Quit(ref missing, ref missing, ref missing);
}
catch (Exception ex)
{
doc.Close(ref missing, ref missing, ref missing);
word.Application.Quit(ref missing, ref missing, ref missing);
}
https://stackoverflow.com/questions/2859312
复制相似问题