如何使用C#,.NET将文本写入word文件

时间:2016-07-13 16:17:07

标签: c# .net winforms

我正在尝试使用c#编写并将一些文本附加到word文件中,但是,我无法获得预期的结果。你可以帮帮我吗?

以下是我的代码 -

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace WFA1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //FileStream F = new FileStream("testdoc2.docx", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            Console.WriteLine("Sourav");           
            string filename = @"C:\\Desktop\\myfile.docx";
            Console.WriteLine(filename);
            try
            {
                using (FileStream fs = File.OpenWrite(filename))
                {
                    Byte[] content = new UTF8Encoding(true).GetBytes("Hello I am learning C#");
                    fs.Write(content, 0, content.Length);
                }
            }
            catch (Exception Ex)
            {
                Console.Write(e.ToString());
            }



        }
    }
}

上面的代码是一个Windows窗体应用程序代码。我使用FileStream类来写数据。但是我面临以下问题: -

  1. 没有创建文件
  2. 代码一直运行,直到我手动停止。
  3. 因此,我也尝试了以下方法,并且我能够将文本写入文件。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;
    using Microsoft.Office.Interop.Word;
    
    namespace WFA1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document doc = app.Documents.Open("C:\\Users\\SS5014874\\Desktop\\testdoc1.docx");
                object missing = System.Reflection.Missing.Value;
                //string s = "Hi";
                //Console.WriteLine(s);               
                doc.Content.Text = textBox1.Text.ToString();
                doc.Save();
                doc.Close(ref missing);
    
                app.Quit(ref missing);
            }
        }
    }
    

    然而,我仍然没有得到预期的结果。以下是我的问题: -

    1. 无法附加任何文字。请让我知道如何使用这种方法追加。有什么方法我们可以调用来附加文本。
    2. 即使我使用过Quit方法,应用程序也不会退出,直到我手动退出。
    3. 此外,我在哪里可以找到班级Microsoft.Office.Interop.Word

      的方法列表

      如有任何其他信息,请与我们联系。

2 个答案:

答案 0 :(得分:1)

请点击此链接https://support.microsoft.com/en-us/kb/316384

您可以尝试此操作。

添加以下指令:

  • 使用Microsoft.Office.Interop.Word;

  • 使用System.Reflection;

用于添加Microsoft.Office.Interop.Word;

  • 在“项目”菜单上,单击“添加引用”。
  • 在“COM”选项卡上,找到“Microsoft Word对象库”,然后选择“选择”。

(在我的情况下,它是 Microsoft Word 12.0对象库

使用这些代码。我正在努力维护这些代码,例如您的代码 -

private void button1_Click(object sender, EventArgs e)
{
   Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();    
   Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(@"e:\testdoc1.docx");
   object missing = System.Reflection.Missing.Value;                        
   doc.Content.Text += textBox1.Text;
   app.Visible = true;    //Optional
   doc.Save();            
   this.Close();           
}

答案 1 :(得分:1)

在这里,您可以动态创建Word文档并在其中编写简单内容

  private async void btn_WriteIntoWord_Click(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word.Document doc; 
        try
        {
            object oMissing = System.Reflection.Missing.Value;

            object missing = System.Reflection.Missing.Value;
            lblProcessing.Text = "Writing File.. Please wait";
            int count=0;

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                doc = app.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                doc.Content.Font.Size = 12;
                doc.Content.Font.Bold = 1;
                if (count != 0) doc.Content.Text = "Dear Team,";
                int innercount = 0;
                foreach (DataGridViewCell cell in row.Cells)
                {
                    innercount++;

                    if (count != 0)
                    {
                        if (cell.Value != null)
                        {

                            await Task.Delay(1);
                            string value = cell.Value.ToString();
                            switch(innercount)
                            {
                                case 1:
                                     doc.Content.Text += "          EC Name: " + value;
                                    break;
                                case 2:
                                     doc.Content.Text += "          SO#: " + value;
                                    break;
                                case 3:
                                    doc.Content.Text += "           Monthly Hire Rate: " + value.Trim();
                                    break;
                                case 4:
                                    doc.Content.Text += "           Bill amount: " + value.Trim();
                                    break;
                                case 5:
                                    doc.Content.Text += "           Project code: " + value;
                                    break;
                                case 6:
                                    doc.Content.Text += "           Line Text: " + value;
                                    break;
                                case 7:
                                    doc.Content.Text += "           Total WD: " + value;
                                    break;
                                case 8:
                                    doc.Content.Text += "           #NPL: " + value;
                                    break;
                                case 9:
                                    doc.Content.Text += "           Project%: " + value;
                                    break;
                                case 10:
                                    doc.Content.Text += "           Remark: " + value;
                                    break;
                                case 11:
                                    doc.Content.Text += "           ALCON Emp ID: " + value;
                                    break;
                                default:
                                    doc.Content.Text += value;
                                    break;

                            }



                        }

                    }
                }

                if (count != 0)
                {
                    doc.Content.Text += "Thanks,";
                    doc.Content.Text += "NCS team";
                    string filecount = "test" + count.ToString() + ".docx";
                    object filename = @"D:\GenerateEmail\EmailBillingRates\EmailBillingRates\Word\" + filecount;
                    doc.SaveAs2(ref filename);
                    doc.Save();
                    doc.Close();
                }
                if (count == 10)
                    break;
                count++;
            }

            app.Visible = true;    //Optional

            lblProcessing.Text = "";
           // MessageBox.Show("File Saved successfully");
            this.Close();

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            Marshal.ReleaseComObject(app);
        }
    }
}