首先引入类库
Microsoft
Office
Interop
Word
然后进行编程
代码如下
using System;
using SystemCollectionsGeneric;
using SystemComponentModel;
using SystemData;
using SystemDrawing;
using SystemText;
using SystemWindowsForms;
using MicrosoftOfficeInteropWord;
namespace WordTest
{
public partial class Form : Form
{
object strFileName;
Object Nothing;
MicrosoftOfficeInteropWordApplication myWordApp = new MicrosoftOfficeInteropWordApplicationClass();
Document myWordDoc;
string strContent = ;
public Form()
{
InitializeComponent();
}
private void button_Click(object sender EventArgs e)
{
createWord();
//openWord();
}
private void createWord()
{
strFileName = SystemWindowsFormsApplicationStartupPath + testdoc;
if (SystemIOFileExists((string)strFileName))
SystemIOFileDelete((string)strFileName);
Object Nothing = SystemReflectionMissingValue;
myWordDoc = myWordAppDocumentsAdd(ref Nothing ref Nothing ref Nothing ref Nothing);
#region 将数据库中读取得数据写入到word文件中
strContent = 你好\n\n\r;
myWordDocParagraphsLastRangeText = strContent;
strContent = 这是测试程序;
myWordDocParagraphsLastRangeText = strContent;
#endregion
//将WordDoc文档对象的内容保存为DOC文档
myWordDocSaveAs(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文档对象
myWordDocClose(ref Nothing ref Nothing ref Nothing);
//关闭WordApp组件对象
myWordAppQuit(ref Nothing ref Nothing ref Nothing);
thisrichTextBoxText = strFileName + \r\n + 创建成功;
}
private void openWord()
{
fontDialogShowDialog();
SystemDrawingFont font = fontDialogFont;
object filepath = D:\\aspdocx;
object oMissing = SystemReflectionMissingValue;
myWordDoc = myWordAppDocumentsOpen(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);
myWordDocContentFontSize = fontSize;
myWordDocContentFontName = fontName;
myWordDocSave();
richTextBoxText = myWordDocContentText;
myWordDocClose(ref oMissing ref oMissing ref oMissing);
myWordAppQuit(ref oMissing ref oMissing ref oMissing);
}
}