C# 将文本从word文件复制到新word
我正在读取word文件中的文本,并从读取的文本中替换一些文本C# 将文本从word文件复制到新word,c#,.net,.net-4.0,ms-word,office-interop,C#,.net,.net 4.0,Ms Word,Office Interop,我正在读取word文件中的文本,并从读取的文本中替换一些文本 var wordApp = new Microsoft.Office.Interop.Word.Application(); object file = path; object nullobj = System.Reflection.Missing.Value; var doc = wordApp.Documents.Open(ref file, ref nullobj, ref nullobj,
var wordApp = new Microsoft.Office.Interop.Word.Application();
object file = path;
object nullobj = System.Reflection.Missing.Value;
var doc = wordApp.Documents.Open(ref file, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj);
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
IDataObject data = Clipboard.GetDataObject();
var text =data.GetData(DataFormats.Text);
所以我有来自原始word文件的文本,现在我需要它传递到一个不存在的新word文件(新文本)
我试过了
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "WINWORD.EXE";
Process.Start(startInfo);
这将打开新的word文件,该文件未物理保存在文件系统中,这很好。但我不确定如何将文本值传递给这个新文件
更新
运行上述代码后,我尝试了
var wordApp = new Microsoft.Office.Interop.Word.Application();
var doc = wordApp.ActiveDocument;
“此命令不可用,因为没有打开的文档。”下面是一个简单的示例,它将整个文本和格式从一个Word文档复制到一个新文档。在新文档中,使用“查找和替换”功能替换文本:
您需要做的就是:
using System.Runtime.InteropServices;
using MSWord = Microsoft.Office.Interop.Word;
namespace ConsoleApplication6
{
class Program
{
static void Main()
{
var application = new MSWord.Application();
var originalDocument = application.Documents.Open(@"C:\whatever.docx");
originalDocument.ActiveWindow.Selection.WholeStory();
var originalText = originalDocument.ActiveWindow.Selection;
var newDocument = new MSWord.Document();
newDocument.Range().Text = originalText.Text;
newDocument.SaveAs(@"C:\whateverelse.docx");
originalDocument.Close(false);
newDocument.Close();
application.Quit();
Marshal.ReleaseComObject(application);
}
}
}
你见过这个:@MUG4N:我见过类似的东西,但我不确定什么是
worddocpromo
。没有explanation@huMptyduMpty您应该依靠word interop来完成此操作,而不是process.start。创建一个新的word文档,设置内容,将其保存到另一个位置,然后使用process.start等从那里打开它。不要忘记正确处理com对象
using System.Runtime.InteropServices;
using MSWord = Microsoft.Office.Interop.Word;
namespace ConsoleApplication6
{
class Program
{
static void Main()
{
var application = new MSWord.Application();
var originalDocument = application.Documents.Open(@"C:\whatever.docx");
originalDocument.ActiveWindow.Selection.WholeStory();
var originalText = originalDocument.ActiveWindow.Selection;
var newDocument = new MSWord.Document();
newDocument.Range().Text = originalText.Text;
newDocument.SaveAs(@"C:\whateverelse.docx");
originalDocument.Close(false);
newDocument.Close();
application.Quit();
Marshal.ReleaseComObject(application);
}
}
}