求C# 给word插入页眉的方法

sunnybo333 sunnybo333 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
调用:string text=textBox14.Text ;
report.SetPageHeader(text);
下面是封装的类
怎么完事页眉一点反应都没有 哪里不对吗?
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Word;

namespace 报告生成软件
{
class Report
{
private _Application wordApp = null;
private _Document wordDoc = null;
public _Application Application
{
get
{
return wordApp;
}
set
{
wordApp = value;
}
}
public _Document Document
{
get
{
return wordDoc;
}
set
{
wordDoc = value;
}
}

//通过模板创建新文档
public void CreateNewDocument(string filePath)
{
killWinWordProcess();
wordApp = new ApplicationClass();
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
wordApp.Visible = false;
object missing = System.Reflection.Missing.Value;
object templateName = filePath;
wordDoc = wordApp.Documents.Open(ref templateName, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
}

//保存新文件
public void SaveDocument(string filePath)
{
object fileName = filePath;
object format = WdSaveFormat.wdFormatDocument;//保存格式
object miss = System.Reflection.Missing.Value;
wordDoc.SaveAs(ref fileName, ref format, ref miss,
ref miss, ref miss, ref miss, ref miss,
ref miss, ref miss, ref miss, ref miss,
ref miss, ref miss, ref miss, ref miss,
ref miss);
//关闭wordDoc,wordApp对象
object SaveChanges = WdSaveOptions.wdSaveChanges;
object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat;
object RouteDocument = false;
wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
}

//在书签处插入值
public bool InsertValue(string bookmark, string value)
{
object bkObj = bookmark;
if (wordApp.ActiveDocument.Bookmarks.Exists(bookmark))
{
wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
wordApp.Selection.TypeText(value);
return true;
}
return false;
}
//插入页眉
public void SetPageHeader(string context)
{
wordApp.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;

wordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;

wordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;

wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(context);

wordApp.Selection.ParagraphFormat.Alignment

= WdParagraphAlignment.wdAlignParagraphCenter;

//跳出页眉设置
wordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;
}

// 杀掉winword.exe进程
public void killWinWordProcess()
{
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");
foreach (System.Diagnostics.Process process in processes)
{
bool b = process.MainWindowTitle == "";
if (process.MainWindowTitle == "")
{
process.Kill();
}
}
}
}
}

...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
sunnybo333
C# 111,128 成员 642,537 内容