简体   繁体   中英

How can I open a Microsoft Word document from within a winforms .exe app?

I have a Winforms app that utilizes a dll (docX) to create a .docx document from a StringBuilder. I'm trying to open that document with Microsoft Word (the default program) with a button click. I tried the folowing code but I keep getting errors. Can someone point me in the right direction to accomplish this?

private void button3_Click(object sender, EventArgs e)
    {
        var x = "";
        using (DocX document = DocX.Create("Testdocx.docx"))
        {
            document.MarginTop = 25f;
            document.MarginBottom = 25f;
            document.MarginLeft = 25f;
            document.MarginRight = 25f;
            Paragraph p = document.InsertParagraph();
            FontFamily fontFamily = new FontFamily("Courier New");

            p.Append(sb.ToString()).Font(fontFamily).FontSize(8); //where "sb" is a StringBuilder
            document.Save();
            x = Environment.CurrentDirectory;
        }
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = @"C:\Program Files (x86)\Microsoft Office\Office12\WINWORD.EXE";
        startInfo.Arguments = x + "\\Testdocx.docx";
        startInfo.UseShellExecute = true;
        Process.Start(startInfo);
    }

Your approach hard-codes the path to WINWORD. While this may work for your case, it is inflexible and brittle.

You can instead simply do

Process.Start(x + "\\Testdocx.docx");

That will find the default document handler for .docx files (which is Winword, assuming it is installed and you have not installed anything else that handles .docx files).

Just change 3 lines in your code. Your problem will be solved

here...

using (DocX document = DocX.Create(Application.StartupPath + "\\Testdocx.docx"))

here

document.Save();
x = Application.StartupPath;

. and here

startInfo.Arguments = "\"" + x + "\\Testdocx.docx\"";  // -> Quotes on either sides

.

. Also I think you dont need to give full path for Word. Just do

 startInfo.FileName = "WINWORD.EXE";

Or even just

 startInfo.FileName = "WINWORD";

传递的参数包括:应用程序,位置

 Process.Start("winword.exe", "C:\\you path here \\filename.docx");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM