如何在C#中使用OpenXml操作Word模版,向Bookmark中填充数据。 100
展开全部
对word的操作给你这个是把word打开 并把其内容 复制出来 你参考一下吧
//btnFindFile_Click(object sender, EventArgs e)中应该按照路径找章节编码,暂时没有实现;
private Microsoft.Office.Interop.Word.ApplicationClass oWordApplic;
private Microsoft.Office.Interop.Word.Document oDoc;
object missing = System.Reflection.Missing.Value;
private List<string> SQlStrList = new List<string>();
private ArrayList arr = new ArrayList();
private string ZJBM = "";
private int C = 0;
public frm导入Word()
{
InitializeComponent();
}
public class objclass
{
public string _value;
public string _text;
public override string ToString()
{
return _text;
}
public objclass(string v, string t)
{
_text = t;
_value = v;
}
public override bool Equals(object obj)
{
return obj.ToString() == this._value;
}
}
private void frmKZQKDR_Load(object sender, EventArgs e)
{
this.cmbTX.SelectedIndex = 0;
基础类.buildTree.Bound难易程度(cmbNYCD);
cmbNYCD.SelectedIndex = -1;
基础类.buildTree.Bound题目类型(cmbTX);
}
private void btnFindFile_Click(object sender, EventArgs e)//将word内容导入到RichTextBox中
{
openFileDialog1.Filter = "(*.doc)|*.doc";
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
txtExcelFile.Text = openFileDialog1.FileName;
//打开word,拷贝内容至RTF
WordHelp();
Open(txtExcelFile.Text);
oWordApplic.Selection.WholeStory();
oWordApplic.Selection.Copy();
richTextBox1.Clear();
richTextBox1.Paste();
Clipboard.Clear();
//避免弹出normal.dot被使用的对话框
oWordApplic.NormalTemplate.Saved = true;
oDoc.Close(ref missing, ref missing, ref missing);
Quit();
start = 0;
//从得到的路径获得当前章节编码(尚未实现)
ZJBM = "";
}
}
#region///word用函数
public Microsoft.Office.Interop.Word.ApplicationClass WordApplication
{
get { return oWordApplic; }
}
public void WordHelp()
{
// activate the interface with the COM object of Microsoft Word
oWordApplic = new Microsoft.Office.Interop.Word.ApplicationClass();
}
public void WordHelp(Microsoft.Office.Interop.Word.ApplicationClass wordapp)
{
oWordApplic = wordapp;
}
// Open a file (the file must exists) and activate it
public void Open(string strFileName)
{
object fileName = strFileName;
object readOnly = false;
object isVisible = true;
oDoc = oWordApplic.Documents.Open(ref fileName, ref missing, ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
oDoc.Activate();
}
// Open a new document
public void Open()
{
oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);
oDoc.Activate();
}
public void Quit()
{
oWordApplic.Application.Quit(ref missing, ref missing, ref missing);
}
/// 打开Word文档,并且返回对象oDoc
/// 完整Word文件路径+名称
/// 返回的Word.Document oDoc对象
public Microsoft.Office.Interop.Word.Document CreateWordDocument(string FileName, bool HideWin)
{
if (FileName == "") return null;
oWordApplic.Visible = HideWin;
oWordApplic.Caption = "";
oWordApplic.Options.CheckSpellingAsYouType = false;
oWordApplic.Options.CheckGrammarAsYouType = false;
Object filename = FileName;
Object ConfirmConversions = false;
Object ReadOnly = false;
Object AddToRecentFiles = false;
Object PasswordDocument = System.Type.Missing;
Object PasswordTemplate = System.Type.Missing;
Object Revert = System.Type.Missing;
Object WritePasswordDocument = System.Type.Missing;
Object WritePasswordTemplate = System.Type.Missing;
Object Format = System.Type.Missing;
Object Encoding = System.Type.Missing;
Object Visible = System.Type.Missing;
Object OpenAndRepair = System.Type.Missing;
Object DocumentDirection = System.Type.Missing;
Object NoEncodingDialog = System.Type.Missing;
Object XMLTransform = System.Type.Missing;
try
{
Microsoft.Office.Interop.Word.Document wordDoc = oWordApplic.Documents.Open(ref filename, ref ConfirmConversions,
ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate, ref Format,
ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection,
ref NoEncodingDialog, ref XMLTransform);
return wordDoc;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
public void SaveAs(Microsoft.Office.Interop.Word.Document oDoc, string strFileName)
{
object fileName = strFileName;
if (File.Exists(strFileName))
{
if (MessageBox.Show("文件'" + strFileName + "'已经存在,选确定覆盖原文件,选取消退出操作!", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
oDoc.SaveAs(ref fileName, 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);
}
else
{
Clipboard.Clear();
}
}
else
{
oDoc.SaveAs(ref fileName, 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 SaveAs(string strFileName)
{
object fileName = strFileName;
oDoc.SaveAs(ref fileName, 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);
}
#endregion
/// <summary>
/// 附加dot模版文件
/// </summary>
private void LoadDotFile(string strDotFile)
{
if (!string.IsNullOrEmpty(strDotFile))
{
Microsoft.Office.Interop.Word.Document wDot = null;
if (oWordApplic != null)
{
oDoc = oWordApplic.ActiveDocument;
oWordApplic.Selection.WholeStory();
string strContent = oWordApplic.Selection.Text;
oWordApplic.Selection.Copy();
wDot = CreateWordDocument(strDotFile, false);
//object bkmC = "Content";
//if (oWordApplic.ActiveDocument.Bookmarks.Exists("Content") == true)
//{
// oWordApplic.ActiveDocument.Bookmarks.get_Item
// (ref bkmC).Select();
//}
//对标签"Content"进行填充
//直接写入内容不能识别表格什么的
//oWordApplic.Selection.TypeText("123123123123123123");
//oWordApplic.Selection.Paste();
oWordApplic.Selection.WholeStory();
oWordApplic.Selection.Copy();
oDoc.Activate();
oWordApplic.Selection.Paste();
wDot.Close(ref missing, ref missing, ref missing);
//给试卷加入内容
object bkmC = "Content1";
if (oWordApplic.ActiveDocument.Bookmarks.Exists("Content1") == true)
{
oWordApplic.ActiveDocument.Bookmarks.get_Item
(ref bkmC).Select();
}
//oWordApplic.Selection.TypeText("123123123123123123456456");
Clipboard.Clear();//清空剪切板
this.richTextBox1.SelectAll();
this.richTextBox1.Cut();
oDoc.Activate();
oWordApplic.Selection.Paste();
}
}
}
public int start = 0;
}
//btnFindFile_Click(object sender, EventArgs e)中应该按照路径找章节编码,暂时没有实现;
private Microsoft.Office.Interop.Word.ApplicationClass oWordApplic;
private Microsoft.Office.Interop.Word.Document oDoc;
object missing = System.Reflection.Missing.Value;
private List<string> SQlStrList = new List<string>();
private ArrayList arr = new ArrayList();
private string ZJBM = "";
private int C = 0;
public frm导入Word()
{
InitializeComponent();
}
public class objclass
{
public string _value;
public string _text;
public override string ToString()
{
return _text;
}
public objclass(string v, string t)
{
_text = t;
_value = v;
}
public override bool Equals(object obj)
{
return obj.ToString() == this._value;
}
}
private void frmKZQKDR_Load(object sender, EventArgs e)
{
this.cmbTX.SelectedIndex = 0;
基础类.buildTree.Bound难易程度(cmbNYCD);
cmbNYCD.SelectedIndex = -1;
基础类.buildTree.Bound题目类型(cmbTX);
}
private void btnFindFile_Click(object sender, EventArgs e)//将word内容导入到RichTextBox中
{
openFileDialog1.Filter = "(*.doc)|*.doc";
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
txtExcelFile.Text = openFileDialog1.FileName;
//打开word,拷贝内容至RTF
WordHelp();
Open(txtExcelFile.Text);
oWordApplic.Selection.WholeStory();
oWordApplic.Selection.Copy();
richTextBox1.Clear();
richTextBox1.Paste();
Clipboard.Clear();
//避免弹出normal.dot被使用的对话框
oWordApplic.NormalTemplate.Saved = true;
oDoc.Close(ref missing, ref missing, ref missing);
Quit();
start = 0;
//从得到的路径获得当前章节编码(尚未实现)
ZJBM = "";
}
}
#region///word用函数
public Microsoft.Office.Interop.Word.ApplicationClass WordApplication
{
get { return oWordApplic; }
}
public void WordHelp()
{
// activate the interface with the COM object of Microsoft Word
oWordApplic = new Microsoft.Office.Interop.Word.ApplicationClass();
}
public void WordHelp(Microsoft.Office.Interop.Word.ApplicationClass wordapp)
{
oWordApplic = wordapp;
}
// Open a file (the file must exists) and activate it
public void Open(string strFileName)
{
object fileName = strFileName;
object readOnly = false;
object isVisible = true;
oDoc = oWordApplic.Documents.Open(ref fileName, ref missing, ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
oDoc.Activate();
}
// Open a new document
public void Open()
{
oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);
oDoc.Activate();
}
public void Quit()
{
oWordApplic.Application.Quit(ref missing, ref missing, ref missing);
}
/// 打开Word文档,并且返回对象oDoc
/// 完整Word文件路径+名称
/// 返回的Word.Document oDoc对象
public Microsoft.Office.Interop.Word.Document CreateWordDocument(string FileName, bool HideWin)
{
if (FileName == "") return null;
oWordApplic.Visible = HideWin;
oWordApplic.Caption = "";
oWordApplic.Options.CheckSpellingAsYouType = false;
oWordApplic.Options.CheckGrammarAsYouType = false;
Object filename = FileName;
Object ConfirmConversions = false;
Object ReadOnly = false;
Object AddToRecentFiles = false;
Object PasswordDocument = System.Type.Missing;
Object PasswordTemplate = System.Type.Missing;
Object Revert = System.Type.Missing;
Object WritePasswordDocument = System.Type.Missing;
Object WritePasswordTemplate = System.Type.Missing;
Object Format = System.Type.Missing;
Object Encoding = System.Type.Missing;
Object Visible = System.Type.Missing;
Object OpenAndRepair = System.Type.Missing;
Object DocumentDirection = System.Type.Missing;
Object NoEncodingDialog = System.Type.Missing;
Object XMLTransform = System.Type.Missing;
try
{
Microsoft.Office.Interop.Word.Document wordDoc = oWordApplic.Documents.Open(ref filename, ref ConfirmConversions,
ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate, ref Format,
ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection,
ref NoEncodingDialog, ref XMLTransform);
return wordDoc;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
public void SaveAs(Microsoft.Office.Interop.Word.Document oDoc, string strFileName)
{
object fileName = strFileName;
if (File.Exists(strFileName))
{
if (MessageBox.Show("文件'" + strFileName + "'已经存在,选确定覆盖原文件,选取消退出操作!", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
oDoc.SaveAs(ref fileName, 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);
}
else
{
Clipboard.Clear();
}
}
else
{
oDoc.SaveAs(ref fileName, 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 SaveAs(string strFileName)
{
object fileName = strFileName;
oDoc.SaveAs(ref fileName, 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);
}
#endregion
/// <summary>
/// 附加dot模版文件
/// </summary>
private void LoadDotFile(string strDotFile)
{
if (!string.IsNullOrEmpty(strDotFile))
{
Microsoft.Office.Interop.Word.Document wDot = null;
if (oWordApplic != null)
{
oDoc = oWordApplic.ActiveDocument;
oWordApplic.Selection.WholeStory();
string strContent = oWordApplic.Selection.Text;
oWordApplic.Selection.Copy();
wDot = CreateWordDocument(strDotFile, false);
//object bkmC = "Content";
//if (oWordApplic.ActiveDocument.Bookmarks.Exists("Content") == true)
//{
// oWordApplic.ActiveDocument.Bookmarks.get_Item
// (ref bkmC).Select();
//}
//对标签"Content"进行填充
//直接写入内容不能识别表格什么的
//oWordApplic.Selection.TypeText("123123123123123123");
//oWordApplic.Selection.Paste();
oWordApplic.Selection.WholeStory();
oWordApplic.Selection.Copy();
oDoc.Activate();
oWordApplic.Selection.Paste();
wDot.Close(ref missing, ref missing, ref missing);
//给试卷加入内容
object bkmC = "Content1";
if (oWordApplic.ActiveDocument.Bookmarks.Exists("Content1") == true)
{
oWordApplic.ActiveDocument.Bookmarks.get_Item
(ref bkmC).Select();
}
//oWordApplic.Selection.TypeText("123123123123123123456456");
Clipboard.Clear();//清空剪切板
this.richTextBox1.SelectAll();
this.richTextBox1.Cut();
oDoc.Activate();
oWordApplic.Selection.Paste();
}
}
}
public int start = 0;
}
展开全部
private void FillBookmarksUsingOpenXml(string sourceDoc, string destDoc, Dictionary<string, string> bookmarkData) { string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; // Make a copy of the template file. File.Copy(sourceDoc, destDoc, true); //Open the document as an Open XML package and extract the main document part. using (WordprocessingDocument wordPackage = WordprocessingDocument.Open(destDoc, true)) { MainDocumentPart part = wordPackage.MainDocumentPart; //Setup the namespace manager so you can perform XPath queries //to search for bookmarks in the part. NameTable nt = new NameTable(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); nsManager.AddNamespace("w", wordmlNamespace); //Load the part's XML into an XmlDocument instance. XmlDocument xmlDoc = new XmlDocument(nt); xmlDoc.Load(part.GetStream()); //Iterate through the bookmarks. foreach (KeyValuePair<string, string> bookmarkDataVal in bookmarkData) { var bookmarks = from bm in part.Document.Body.Descendants<BookmarkStart>() select bm; foreach (var bookmark in bookmarks) { if (bookmark.Name == bookmarkDataVal.Key) { Run bookmarkText = bookmark.NextSibling<Run>(); if (bookmarkText != null) // if the bookmark has text replace it { bookmarkText.GetFirstChild<Text>().Text = bookmarkDataVal.Value; } else // otherwise append new text immediately after it { var parent = bookmark.Parent; // bookmark's parent element Text text = new Text(bookmarkDataVal.Value); Run run = new Run(new RunProperties()); run.Append(text); // insert after bookmark parent parent.Append(run); } //bk.Remove(); // we don't want the bookmark anymore } } } //Write the changes back to the document part. xmlDoc.Save(wordPackage.MainDocumentPart.GetStream(FileMode.Create)); } }
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询