c#

位置:IT落伍者 >> c# >> 浏览文章

C#操作Word文档(Office 2007)


发布日期:2023年06月10日
 
C#操作Word文档(Office 2007)
首先引入类库MicrosoftOfficeInteropWord然后进行编程代码如下

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);

}

}

上一篇:C#中正则表达式进行忽略大小写的字符串替换

下一篇:深入解析C#编程中的事件