C#操作Word文档

上一篇 / 下一篇  2007-09-25 18:09:30 / 个人分类:C#

首先引入类库,Microsoft.Office.Interop.Word,然后进行编程。代码如下:
首先引入类库,Microsoft.Office.Interop.Word,然后进行编程。代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
usingMicrosoft.Office.Interop.Word;

namespaceWordTest
{
public partial class Form1 : Form
{
object strFileName;
Object Nothing;
Microsoft.Office.Interop.Word.Application myWordApp = newMicrosoft.Office.Interop.Word.ApplicationClass();
Document myWordDoc;
string strContent = "";

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
createWord();
//openWord();
}

private void createWord()
{
strFileName = System.Windows.Forms.Application.StartupPath + "test.doc";
if (System.IO.File.Exists((string)strFileName))
System.IO.File.Delete((string)strFileName);
Object Nothing = System.Reflection.Missing.Value;
myWordDoc = myWordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

#region 将数据库中读取得数据写入到word文件中

strContent = "你好nnr";
myWordDoc.Paragraphs.Last.Range.Text = strContent;

strContent = "这是测试程序";
myWordDoc.Paragraphs.Last.Range.Text = strContent;


#endregion

//将WordDoc文档对象的内容保存为DOC文档
myWordDoc.SaveAs(ref strFileName, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//关闭WordDoc文档对象
myWordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭WordApp组件对象
myWordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

this.richTextBox1.Text = strFileName + "rn" + "创建成功";

}
private void openWord()
{
fontDialog1.ShowDialog();
System.Drawing.Font font = fontDialog1.Font;
object filepath = "D:asp.docx";
object ōMissing = System.Reflection.Missing.Value;
myWordDoc = myWordApp.Documents.Open(ref filepath, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
myWordDoc.Content.Font.Size = font.Size;
myWordDoc.Content.Font.Name = font.Name;
myWordDoc.Save();
richTextBox1.Text = myWordDoc.Content.Text;


myWordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
myWordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
}

}

TAG:

Bamboo's blog 引用 删除 Gisbamboo   /   2008-10-11 19:55:41
3
引用 删除 Guest   /   2008-10-10 14:56:40
5
做最权威的导航专家_hehy 引用 删除 hehy   /   2007-09-26 14:37:26
3
不错,学习学习!
 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2008-10-18  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 7278
  • 日志数: 40
  • 建立时间: 2007-08-10
  • 更新时间: 2008-03-11

RSS订阅

Open Toolbar