Reputation: 504
I am trying to write and append some text to a word file using c#, however, I am unable to get expected results. Could you please help me out of this ?
Below is my code-
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());
}
}
}
}
The above code is a windows form application code behind. I have use FileStream class to write data. However I am facing below issues :-
- No file is getting created
- Code keeps on running until I stop it manually.
Hence, I tried the below approach too, and I was able to write text to the file.
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);
}
}
}
However, still I did not get expected results. below are my issues:-
- Unable to append any text. Please let me know how to append using this approach. is there any method we can call to append texts.
- Even though I have used Quit method, application is not quitting, until I quit manually.
Also, where can I find the list of methods of class Microsoft.Office.Interop.Word
Please let me know for any other information.
Upvotes: 2
Views: 38211
Reputation: 2625
There is Open-XML-SDK (a set of tools from Microsoft to work with Office documents like Word, Excel, and PowerPoint).
The official repo mentioned OfficeIMO (a library that is built on top of OpenXML to work with Word documents).
Here is a sample code for creating docx file using OfficeIMO
var content = "This is a newly created docx document! " +
$"at {DateTime.Now.ToString(CultureInfo.InvariantCulture)}";
var path = "text.docx";
using var document = WordDocument.Create(path);
var paragraph = document.AddParagraph(content);
document.Save();
No need for any other dependencies (like Microsoft.Office.Interop.Word), nor having Office installed at all!
Upvotes: 0
Reputation: 31
Here you dynamically create word document and write simple content in it
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);
}
}
}
Upvotes: 1
Reputation: 176
Please follow this link https://support.microsoft.com/en-us/kb/316384
Or
You can try this.
Add the following directives:
using Microsoft.Office.Interop.Word;
using System.Reflection;
For adding Microsoft.Office.Interop.Word;
(In my case it is Microsoft Word 12.0 Object Library)
Use these codes. I am trying to maintain these codes like your codes -
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();
}
Upvotes: 4