C#操作Word書簽?zāi)0?/p>
一制作模板
1 新建一個(gè)文檔,設(shè)置文檔內(nèi)容。對(duì)于循環(huán)的部分,建議放到表格內(nèi),這樣容易定位、選擇、復(fù)制、粘貼。
2 將鼠標(biāo)定位到要插入書簽的位置,從菜單上,“插入”->“書簽”,彈出對(duì)話框,輸入書簽名,點(diǎn)擊“添加”按鈕。
插入以下書簽:order_num,報(bào)告日期_,報(bào)表模板__,name,age,結(jié)論__
其中,報(bào)表模板__,用于定位模板表格。可有可無,沒有時(shí),默認(rèn)表格1。
完成后,所有書簽的名稱和位置如下圖所示:
3 保存模板,比如“word書簽?zāi)0?doc”
二 添加引用
1 右擊“解決方案資源管理器”中的項(xiàng)目目錄下的“引用”,選擇“添加引用”,打開“添加引用”對(duì)話框
2 對(duì)于WindowsForm方式時(shí),在“添加引用”-->“COM”-->“Microsoft Word 11.0Object Library”,點(diǎn)擊“確定”
3對(duì)于WebSite網(wǎng)站方式時(shí),打開“添加引用”-->“瀏覽”項(xiàng)-->”Microsoft.Office.Interop.Word.dll”文件,選中它,點(diǎn)擊“確定”
注意:此處要查找的“Microsoft.Office.Interop.Word.dll”版本必須為“11.*.*.*”,“*”代表數(shù)字
以上版本對(duì)應(yīng)是 Office Word 2003版本。
三 編譯執(zhí)行
如果編譯時(shí)產(chǎn)生錯(cuò)誤 CS1752:無法嵌入互操作類型“Microsoft.Office.Interop.Word.ApplicationClass”。請(qǐng)改用適用的接口。
,那么,點(diǎn)擊 “解決方案”下“工程名稱”之下的“引用”之下的Word,在其屬性下,將“潛入互操作類型”,由true改為false即可。
運(yùn)行結(jié)過如下:
四 主要的代碼如下:
1 首先引用(WindowsForm):M[]icrosoft Word 11.0 Object Library
或者引用(WebSite):Microsoft.Office.Interop.Word.dll
2 在使用的程序中,加入以下語句
using Word = Microsoft.Office.Interop.Word;
===== 1 主操作界面代碼 ===
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
using word_namespace;
namespace winFormApp_word_bookmark
{
publicpartial class Form1 : Form
{
private object missing = System.Reflection.Missing.Value;
WordHelper wdHelp;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
wdHelp = new WordHelper();
wdHelp.CreateOneDocument("c:\ii.doc", missing, missing,missing);
//1 這里簡(jiǎn)單生成樣例數(shù)據(jù)表,工作中要以實(shí)際的數(shù)據(jù)集為準(zhǔn)
DataTable dt = new DataTable();
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("age", typeof(int));
DataRow dr = dt.NewRow();
dr["name"] = "張三"; dr["age"] = 20;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["name"] = "李四"; dr["age"] = 25;
dt.Rows.Add(dr);
//2 調(diào)用模板替換函數(shù),生成實(shí)際的數(shù)據(jù)
SetNameCellValue(dt);
wdHelp.SaveAs("c:\bb.doc");
wdHelp.Close();
MessageBox.Show("ok");
}
public void SetNameCellValue(DataTable dt)
{
//(一) 這里設(shè)置表頭的項(xiàng)目,比如報(bào)表日期
//特別注意:為了容易起見,命名單元格的規(guī)則如下,注意:word中書簽不能以下劃線開頭,可能是保留的書簽使用
//1.1 開頭處的命名單元格,以1個(gè)下劃線結(jié)尾,比如,報(bào)告日期_
//1.2 中間循環(huán)命名單元格,就是正常的,與數(shù)據(jù)集的字段名一致為好
//1.3 結(jié)尾處的命名單元格,以2個(gè)下劃線結(jié)尾,比如,合計(jì)__
try
{//為了程序自動(dòng)處理方便起見
wdHelp.GoToBookMark("報(bào)告日期_");//開始處的命名單元格,都以1個(gè)下劃線_結(jié)尾
wdHelp.InsertText(DateTime.Now.ToString("yyyy-MM-ddhh:mm:ss"));
}
catch (System.Exception ex)
{
}
//(二) 根據(jù)數(shù)據(jù)源的個(gè)數(shù),設(shè)置重復(fù)變化的數(shù)據(jù)行組,
//1 聲明與命名單元格相關(guān)的變量和數(shù)組
int min_Row = 65536, min_Col = 65536, max_Row = 0;
string min_Name = "";
int nameCellCount =wdHelp.wordDoc.Bookmarks.Count;//獲得命名單元格的總數(shù)
int[] nameCellRow = new int[nameCellCount];//某個(gè)命名單元格的行
int[] nameCellColumn = new int[nameCellCount];//某個(gè)命名單元格的列
string[] nameCellTag = new string[nameCellCount];//某個(gè)命名單元格的常規(guī)地址 ,比如$A$1
string[] nameCellName = newstring[nameCellCount];//某個(gè)命名單元格的自定義名稱,比如 工資
string strName, str;
int row1, row2;//選擇重復(fù)的行
int nameCellIdx = 0;
Word.Range tmpRange,srcRange,desRange;
//2 尋找所有命名的單元格,并找到行號(hào)最小者,以便在它之前插入循環(huán)行
for (int k = 0; k < nameCellCount; k++)
{
strName = wdHelp.wordDoc.Bookmarks[k + 1].Name;//
str = strName.Substring(strName.Length - 1, 1);
if (str == "_")
{
continue;//如果第一個(gè)字符為下劃線,則認(rèn)為是固定命名單元格,不是命名的循環(huán)單元格
}
try
{
tmpRange = wdHelp.wordDoc.Bookmarks.get_Item(strName).Range;
nameCellColumn[nameCellIdx] = tmpRange.Cells[1].ColumnIndex;//app.ActiveCell.Column;
nameCellRow[nameCellIdx] =tmpRange.Cells[1].RowIndex;//app.ActiveCell.Row;
nameCellName[nameCellIdx] = strName;
nameCellTag[nameCellIdx] = "";//app.ActiveCell.Address;//$A$1
nameCellTag[nameCellIdx] = "";//nameCellTag[nameCellIdx].Split('$')[1];//$A$1--> A
if (min_Row > nameCellRow[nameCellIdx])
{
min_Row = nameCellRow[nameCellIdx];//最小的行號(hào)
min_Col = nameCellColumn[nameCellIdx];
min_Name = nameCellName[nameCellIdx];
}
if (max_Row < nameCellRow[nameCellIdx]) max_Row =nameCellRow[nameCellIdx]; ;//最大行號(hào)
nameCellIdx++;//真實(shí)的循環(huán)的命名單元格序號(hào)
}
catch (System.Exception ex)
{
}
}
nameCellCount = nameCellIdx;//實(shí)際要處理的循環(huán)的命名單元格數(shù)目
int loopRow = max_Row - min_Row + 1;//一次循環(huán)的函數(shù)
//3 也可以使用 //foreach ( Word.Bookmark bk inwh.wordDoc.Bookmarks)MessageBox.Show(bk.Name);
Word.Table operTable;
// 方法1 通常使用第一個(gè)表來作為模板表
operTable = wdHelp.wordDoc.Tables[1];
// 方法2 使用一個(gè)書簽來標(biāo)志模板表
try
{//使用一個(gè)特殊的標(biāo)簽 table_bookmark_template_
tmpRange =wdHelp.wordDoc.Bookmarks.get_Item("報(bào)表模板__").Range;//
operTable = tmpRange.Tables[1];//得到該書簽所在的表,以它為報(bào)表的循環(huán)模板
}
catch (System.Exception ex)
{
}
//
int template_start = 0;
int template_end = 0;
int table_columns=operTable.Columns.Count;//本表格的烈數(shù)
tmpRange = operTable.Cell(min_Row,1).Range;
template_start =tmpRange.Start;//循環(huán)行組的第一行,第一個(gè)單元格,到文檔開頭的距離
tmpRange = operTable.Cell(max_Row, table_columns).Range;
template_end = tmpRange.Start; //循環(huán)行組的最后行,最后一個(gè)單元格,到文檔開頭的距離
srcRange = operTable.Cell(1, 1).Range;
desRange = operTable.Cell(1, 1).Range;
//4 根據(jù)數(shù)據(jù)集的實(shí)際數(shù)據(jù)行數(shù),查找命名單元格,循環(huán)插入數(shù)據(jù)
int cur_row = min_Row;//0;// min_Row;//
for (int dt_row_idx = 0; dt_row_idx
{//循環(huán)實(shí)際的數(shù)據(jù)行數(shù)
//goto xx1;//跳過方法1
//方法1 整體多行組,復(fù)制和粘貼,看起來復(fù)雜
//4.1 找到行號(hào)最小的循環(huán)行組的命名單元格,以它來定位
tmpRange =wdHelp.wordDoc.Bookmarks.get_Item(min_Name).Range;//app.Goto(min_Name);
//4.2 //插入循環(huán)重復(fù)的摸板行組的行,使得所有命名單元格都向后移,以便下次循環(huán)查找定位使用
// for (int j = 0; j < loopRow; j++)
// {//插入需要重復(fù)循環(huán)的行數(shù)loopRow的空行
//app.ActiveCell.EntireRow.Insert();
// }
//4.3 定位到摸板行組首行
tmpRange =wdHelp.wordDoc.Bookmarks.get_Item(min_Name).Range;//轉(zhuǎn)到摸板行組的行號(hào)最小的命名單元格,以它來定位
row1 = tmpRange.Cells[1].RowIndex;//a//摸板行組的第一行
row2 = row1 + loopRow - 1; //摸板行組的最后一行
template_start = operTable.Cell(row1, 1).Range.Start;
//template_end = operTable.Cell(row2,table_columns).Range.Start;//這樣少一列
template_end = operTable.Cell(row2+1,1).Range.Start;//到下一行,第一個(gè)單元格
//4.4 復(fù)制整體模板的多行組,固定的摸板的格式和相關(guān)的文字說明,也可一個(gè)一個(gè)單元格復(fù)制
srcRange.SetRange(template_start, template_end);//整體多行組復(fù)制摸板行組
srcRange.Copy();
//4.5 定位到新加入行的第一個(gè)單元格內(nèi)
//row1 = row1 - loopRow;//向上回退到新加入的行組
//row2 = row2 - loopRow;
//4.6 粘貼整體多行組,固定的摸板的格式和相關(guān)的文字說明
desRange = operTable.Rows[row1].Range;//整體多行組粘貼摸板行組
desRange.Paste();
xx1:
gotoxx2;//跳過方法2
//方法2 一行一行復(fù)制粘貼,代碼很少
for (int j = 0; j < loopRow; j++)
{//插入需要重復(fù)循環(huán)的行數(shù)loopRow的空行,一行一行的復(fù)制粘貼
//復(fù)制模板行
srcRange=operTable.Rows[cur_row + j + j].Range;//所以,粘貼幾行,就要多加幾行,j+j
srcRange.Copy();
//粘貼到目標(biāo)行
desRange=operTable.Rows[cur_row + j].Range;//因?yàn)?,新粘貼的行在原來模板行的上面
desRange.Paste();
}
cur_row += loopRow;
xx2:
//4.7 動(dòng)態(tài)的數(shù)值加入
for (int name_cell_idx = 0; name_cell_idx < nameCellCount;name_cell_idx++)
{//循環(huán)命名單元格數(shù)量
//str = string.Format("{0}{1}", nameCellTag[name_cell_idx],nameCellRow[name_cell_idx]);
if (nameCellName[name_cell_idx].ToString() == "order_num")
{//序號(hào)
str = string.Format("{0}", dt_row_idx + 1);
}
else
{//以命名單元格的名稱,來取數(shù)據(jù)表行的對(duì)應(yīng)字段的值
str =dt.Rows[dt_row_idx][nameCellName[name_cell_idx]].ToString();
}
//wdHelp.wordDoc.Tables[1].Cell(nameCellRow[name_cell_idx],nameCellColumn[name_cell_idx]).Range.Text = str;
operTable.Cell(nameCellRow[name_cell_idx],nameCellColumn[name_cell_idx]).Range.Text = str;
nameCellRow[name_cell_idx] +=loopRow;//行號(hào)增加重復(fù)行的個(gè)數(shù)loopRow,準(zhǔn)備下個(gè)循環(huán),定位行使用
}
}
// 5 刪除重復(fù)的摸板行,不再需要
//方法1 多行組一次刪除
tmpRange =wdHelp.wordDoc.Bookmarks.get_Item(min_Name).Range;//找到行號(hào)最小的命名單元格,以它來定位
row1 = tmpRange.Cells[1].RowIndex;//app.ActiveCell.Row;
row2 = row1 + loopRow - 1;//選擇重復(fù)的行
template_start = operTable.Cell(row1, 1).Range.Start;
//template_end = operTable.Cell(row2,table_columns).Range.Start;//這樣少一列
template_end = operTable.Cell(row2 + 1,1).Range.Start;//到下一行,第一個(gè)單元格
tmpRange.SetRange(template_start, template_end);//整體多行組復(fù)制摸板行組
tmpRange.Cut();
goto mm2://跳過方法2
//方法2 一行一行地刪除
tmpRange =wdHelp.wordDoc.Bookmarks.get_Item(min_Name).Range;//找到行號(hào)最小的命名單元格,以它來定位
row1 = tmpRange.Cells[1].RowIndex;//app.ActiveCell.Row;
row2 = row1 + loopRow - 1;//選擇重復(fù)的行
for (int dd = 0; dd < loopRow; dd++)
{
operTable.Rows[row1].Delete();//同樣的行號(hào),因?yàn)閯h除前面的,后面向前移動(dòng)
}
mm2:
//(三) 清除剪貼板,避免Excel關(guān)閉工作簿的時(shí)候出現(xiàn)提示
//1 刪除剪切板的內(nèi)容,防止退出提示
//app.CutCopyMode =flase;//Excel.XlCutCopyMode.xlCut;//刪除剪切板的內(nèi)容,防止退出提示
//2 直接用range("A1").copy就行,不必把剪貼板都清空,這會(huì)影響其他進(jìn)程的工作的
//ws.Range[ws.Cells[1, 1], ws.Cells[1, 1]].Copy();
//wdHelp.wordDoc.Tables[1].Cell(1, 1).Range.Copy();
operTable.Cell(1, 1).Range.Copy();
//(四) 結(jié)尾方面的工作
try
{//為了程序自動(dòng)處理方便起見
wdHelp.GoToBookMark("結(jié)論__");//結(jié)尾處的命名單元格,都以2個(gè)下劃線__結(jié)尾
wdHelp.InsertText("成功完成");
}
catch (System.Exception ex)
{
}
}
}
}
===== 2 整理成c# 操作 word的類函數(shù)===
//http://blog.csdn.net/skyering/article/details/8514879
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Word = Microsoft.Office.Interop.Word;
namespace word_namespace //CrossDomain.WebFinder
{
public classWordHelper
{
public Word.ApplicationClass wordApp;
public Word.Document wordDoc;
object missing = System.Reflection.Missing.Value;
public Word.ApplicationClass WordApplication
{
get
{
return wordApp;// _wordApplication;
}
}
public Word.Document WordDocument
{
get
{
return wordDoc;
}
}
public WordHelper()
{
wordApp = new Word.ApplicationClass();//_wordApplication
}
public WordHelper(Word.ApplicationClass wordApplication)
{
wordApp = wordApplication;//_wordApplication
}
public void CreateAndActive()
{
wordDoc = CreateOneDocument(missing, missing, missing,missing);
wordDoc.Activate();
}
public bool OpenAndActive(string FileName, bool IsReadOnly, boolIsVisibleWin)
{
if (string.IsNullOrEmpty(FileName))
{
return false;
}
try
{
wordDoc = OpenOneDocument(FileName, missing, IsReadOnly, missing,missing, missing, missing, missing, missing, missing, missing,IsVisibleWin, missing, missing, missing, missing);
wordDoc.Activate();
return true;
}
catch
{
return false;
}
}
public void Close()
{
if (wordDoc != null)
{
wordDoc.Close(ref missing, ref missing, ref missing);
wordApp.Application.Quit(ref missing, ref missing, refmissing);//_wordApplication
}
}
public void Save()
{
if (wordDoc == null)
{
wordDoc = wordApp.ActiveDocument;//_wordApplication
}
wordDoc.Save();
}
public void SaveAs(string FileName)
{
if (wordDoc == null)
{
wordDoc = wordApp.ActiveDocument;//_wordApplication
}
object objFileName = FileName;
wordDoc.SaveAs(ref objFileName, ref missing, ref missing, refmissing, 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 Word.Document CreateOneDocument(object template, objectnewTemplate, object documentType, object visible)
{
return wordDoc = wordApp.Documents.Add(ref template, refnewTemplate, ref documentType, refvisible);//_wordApplication
}
public Word.Document OpenOneDocument(object FileName, objectConfirmConversions, object ReadOnly,
object AddToRecentFiles, object PasswordDocument, objectPasswordTemplate, object Revert,
object WritePasswordDocument, object WritePasswordTemplate, objectFormat, object Encoding,
object Visible, object OpenAndRepair, object DocumentDirection,object NoEncodingDialog, object XMLTransform)
{
try
{//_wordApplication
// return wordApp.Documents.Add(ref FileName, refConfirmConversions, ref ReadOnly, ref AddToRecentFiles,
return wordApp.Documents.Open(ref FileName, ref ConfirmConversions,ref ReadOnly, ref AddToRecentFiles,
ref PasswordDocument, ref PasswordTemplate, ref Revert, refWritePasswordDocument, ref WritePasswordTemplate,
ref Format, ref Encoding, ref Visible, ref OpenAndRepair, refDocumentDirection, ref NoEncodingDialog, ref XMLTransform);
}
catch
{
return null;
}
}
public bool GoToBookMark(string bookMarkName)
{
//是否存在書簽
if (wordDoc.Bookmarks.Exists(bookMarkName))
{
object what = Word.WdGoToItem.wdGoToBookmark;
object name = bookMarkName;
GoTo(what, missing, missing, name);
return true;
}
return false;
}
public void GoTo(object what, object which, object count, objectname)
{
wordApp.Selection.GoTo(ref what, ref which, ref count, refname);//_wordApplication
}
public void ReplaceBookMark(string bookMarkName, string text)
{
bool isExist = GoToBookMark(bookMarkName);
if (isExist)
{
InsertText(text);
}
}
public bool Replace(string oldText, string newText, stringreplaceType, bool isCaseSensitive)
{
if (wordDoc == null)
{
wordDoc = wordApp.ActiveDocument;//_wordApplication
}
object findText = oldText;
object replaceWith = newText;
object wdReplace;
object matchCase = isCaseSensitive;
switch (replaceType)
{
case "All":
wdReplace =Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
break;
case "None":
wdReplace =Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
break;
case "FirstOne":
wdReplace =Microsoft.Office.Interop.Word.WdReplace.wdReplaceOne;
break;
default:
wdReplace =Microsoft.Office.Interop.Word.WdReplace.wdReplaceOne;
break;
}
wordDoc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式設(shè)置
return wordDoc.Content.Find.Execute(ref findText, ref matchCase,ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,ref replaceWith,
ref wdReplace, ref missing, ref missing, ref missing, refmissing);
}
public void InsertText(string text)
{
wordApp.Selection.TypeText(text);//_wordApplication
}
public void InsertLineBreak()
{
wordApp.Selection.TypeParagraph();//_wordApplication
}
public void InsertPageBreak()
{
//插入分頁if(i!=DT.Rows.Count-1)
{
object mymissing = System.Reflection.Missing.Value;
object myunit = Word.WdUnits.wdStory;
wordApp.Selection.EndKey(ref myunit, ref mymissing);
object pBreak = (int)Word.WdBreakType.wdPageBreak;
wordApp.Selection.InsertBreak(ref pBreak);
}
}
public void InsertPic(string fileName)
{
object range = wordApp.Selection.Range;//_wordApplication
InsertPic(fileName, missing, missing, range);
}
public void InsertPic(string fileName, float width, floatheight)
{
object range = wordApp.Selection.Range;//_wordApplication
InsertPic(fileName, missing, missing, range, width, height);
}
public void InsertPic(string fileName, float width, float height,string caption)
{
object range = wordApp.Selection.Range;//_wordApplication
InsertPic(fileName, missing, missing, range, width, height,caption);
}
public void InsertPic(string FileName, object LinkToFile, objectSaveWithDocument, object Range, float Width, float Height, stringcaption)
{//_wordApplication
wordApp.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile,ref SaveWithDocument, ref Range).Select();
if (Width > 0)
{
wordApp.Selection.InlineShapes[1].Width =Width;//_wordApplication
}
if (Height > 0)
{
wordApp.Selection.InlineShapes[1].Height =Height;//_wordApplication
}
object Label = Word.WdCaptionLabelID.wdCaptionFigure;
object Title = caption;
object Title;
object Position =Word.WdCaptionPosition.wdCaptionPositionBelow;
object ExcludeLabel = true;
wordApp.Selection.InsertCaption(ref Label, ref Title, refTitleAutoText, ref Position, refExcludeLabel);//_wordApplication
MoveRight();
}
public void InsertPic(string FileName, object LinkToFile, objectSaveWithDocument, object Range, float Width, float Height)
{
wordApp.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile,ref SaveWithDocument, ref Range).Select();//_wordApplication
wordApp.Selection.InlineShapes[1].Width =Width;//_wordApplication
wordApp.Selection.InlineShapes[1].Height =Height;//_wordApplication
MoveRight();
}
public void InsertPic(string FileName, object LinkToFile, objectSaveWithDocument, object Range)
{
wordApp.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile,ref SaveWithDocument, ref Range);//_wordApplication
}
public void InsertBookMark(string bookMarkName)
{
//存在則先刪除
if (wordDoc.Bookmarks.Exists(bookMarkName))
{
DeleteBookMark(bookMarkName);
}
object range = wordApp.Selection.Range;//_wordApplication
wordDoc.Bookmarks.Add(bookMarkName, ref range);
}
public void DeleteBookMark(string bookMarkName)
{
if (wordDoc.Bookmarks.Exists(bookMarkName))
{
var bookMarks = wordDoc.Bookmarks;
for (int i = 1; i <= bookMarks.Count; i++)
{
object index = i;
var bookMark = bookMarks.get_Item(ref index);
if (bookMark.Name == bookMarkName)
{
bookMark.Delete();
break;
}
}
}
}
public void DeleteAllBookMark()
{
for (; wordDoc.Bookmarks.Count > 0; )
{
object index = wordDoc.Bookmarks.Count;
var bookmark = wordDoc.Bookmarks.get_Item(ref index);
bookmark.Delete();
}
}
public Word.Table AddTable(int NumRows, int NumColumns)
{
return AddTable(wordApp.Selection.Range, NumRows, NumColumns,missing, missing);//_wordApplication
}
public Word.Table AddTable(int NumRows, int NumColumns,Word.WdAutoFitBehavior AutoFitBehavior)
{
return AddTable(wordApp.Selection.Range, NumRows, NumColumns,missing, AutoFitBehavior);//_wordApplication
}
public Word.Table AddTable(Word.Range Range, int NumRows, intNumColumns, object DefaultTableBehavior, objectAutoFitBehavior)
{
if (wordDoc == null)
{
wordDoc = wordApp.ActiveDocument;//_wordApplication
}
return wordDoc.Tables.Add(Range, NumRows, NumColumns, refDefaultTableBehavior, ref AutoFitBehavior);
}
public Word.Row AddRow(Word.Table table)
{
return AddRow(table, missing);
}
public Word.Row AddRow(Word.Table table, object beforeRow)
{
return table.Rows.Add(ref beforeRow);
}
public void InsertRows(int numRows)
{
object NumRows = numRows;
object wdCollapseStart =Word.WdCollapseDirection.wdCollapseStart;
wordApp.Selection.InsertRows(ref NumRows);//_wordApplication
wordApp.Selection.Collapse(refwdCollapseStart);//_wordApplication
}
public void MoveLeft(Word.WdUnits unit = Word.WdUnits.wdCharacter,int count = 1, int extend_flag = 0)
{
object extend;
if (extend_flag == 1) extend = Word.WdMovementType.wdExtend;
else extend = missing;
wordApp.Selection.MoveLeft(unit, count,extend);//_wordApplication
}
public void MoveUp(Word.WdUnits unit = Word.WdUnits.wdCharacter,int count = 1, int extend_flag = 0)
{
object extend;
if (extend_flag == 1) extend = Word.WdMovementType.wdExtend;
else extend = missing;
wordApp.Selection.MoveUp(unit, count,extend);//_wordApplication
}
public void MoveRight(Word.WdUnits unit = Word.WdUnits.wdCharacter,int count = 1, int extend_flag = 0)
{
object extend;
if (extend_flag == 1) extend = Word.WdMovementType.wdExtend;
else extend = missing;
wordApp.Selection.MoveRight(unit, count,extend);//_wordApplication
}
public void MoveDown(Word.WdUnits unit = Word.WdUnits.wdCharacter,int count = 1, int extend_flag = 0)
{
object extend;
if (extend_flag == 1) extend = Word.WdMovementType.wdExtend;
else extend = missing;
wordApp.Selection.MoveDown(unit, count,extend);//_wordApplication
}
//2 另外的地方復(fù)制過來
public void SetLinesPage(int size = 40)
{
wordApp.ActiveDocument.PageSetup.LinesPage = size;
}
public void SetPageHeaderFooter(string context, int HeaderFooter =0)
{
//wordApp.ActiveWindow.View.Type =Word.WdViewType.wdOutlineView;
//wordApp.ActiveWindow.View.SeekView =Word.WdSeekView.wdSeekPrimaryHeader;
//wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(context);
//wordApp.Selection.ParagraphFormat.Alignment =Word.WdParagraphAlignment.wdAlignParagraphCenter;
//跳出頁眉設(shè)置
//wordApp.ActiveWindow.View.SeekView =Word.WdSeekView.wdSeekMainDocument;
//
////添加頁眉方法二:
if (wordApp.ActiveWindow.ActivePane.View.Type ==Word.WdViewType.wdNormalView ||
wordApp.ActiveWindow.ActivePane.View.Type ==Word.WdViewType.wdOutlineView)
{
wordApp.ActiveWindow.ActivePane.View.Type =Word.WdViewType.wdPrintView;
}
if (HeaderFooter == 0)
{//設(shè)置頁眉內(nèi)容";
wordApp.ActiveWindow.View.SeekView =Word.WdSeekView.wdSeekCurrentPageHeader;
}
else
{//設(shè)置頁腳內(nèi)容";
wordApp.ActiveWindow.View.SeekView =Word.WdSeekView.wdSeekCurrentPageFooter;
}
wordApp.Selection.HeaderFooter.LinkToPrevious = false;
wordApp.Selection.HeaderFooter.Range.ParagraphFormat.Alignment =Word.WdParagraphAlignment.wdAlignParagraphCenter;
wordApp.Selection.HeaderFooter.Range.Text = context;// "頁眉 頁腳內(nèi)容";
//跳出頁眉頁腳設(shè)置
wordApp.ActiveWindow.View.SeekView =Word.WdSeekView.wdSeekMainDocument;
}
public void InsertFormatText(string context, int fontSize,Word.WdColor fontColor, int fontBold, string familyName,Word.WdParagraphAlignment align)
{
//設(shè)置字體樣式以及方向
wordApp.Application.Selection.Font.Size = fontSize;
wordApp.Application.Selection.Font.Bold = fontBold;
wordApp.Application.Selection.Font.Color = fontColor;
wordApp.Selection.Font.Name = familyName;
wordApp.Application.Selection.ParagraphFormat.Alignment =align;
wordApp.Application.Selection.TypeText(context);
}
public Word.Table CreatTable(int rowNum, int cellNum)
{
return this.wordDoc.Tables.Add(wordApp.Selection.Range, rowNum,cellNum, ref missing, ref missing);
}
public void setPageLay(string paper = "A4", int orient = 0)
{
//頁面設(shè)置,設(shè)置頁面為縱向布局,設(shè)置紙張類型為A4紙
if (orient == 0)
{
wordDoc.PageSetup.Orientation =Word.WdOrientation.wdOrientLandscape;
}
else
{
wordDoc.PageSetup.Orientation =Word.WdOrientation.wdOrientPortrait;
}
if (paper == "A4")
{
wordDoc.PageSetup.PageWidth =wordApp.CentimetersToPoints(29.7F);
wordDoc.PageSetup.PageHeight =wordApp.CentimetersToPoints(21F);
}
}
public Word.Table getTable(int index)
{
// inttable_num = this.wordDoc.Tables.Count;
//Word.Tables tables = wordDoc.Tables;
// returnwordDoc.Content.Tables[index];
//wordDoc.Tables.Item(index);
int no = 0;
foreach (Word.Table table in wordDoc.Tables)//tables)
{
if (no == index) return table;
no++;
}
return null;
}
public void SetColumnWidth(float[] widths, Word.Table tb)
{
if (widths.Length > 0)
{
int len = widths.Length;
for (int i = 0; i < len; i++)
{
tb.Columns[i + 1].Width = widths[i];
}
}
}
public void MergeColumn(Word.Table tb, Word.Cell[] cells)
{
if (cells.Length > 1)
{
Word.Cell c = cells[0];
int len = cells.Length;
for (int i = 1; i < len; i++)
{
c.Merge(cells[i]);
}
}
wordApp.Selection.Cells.VerticalAlignment =Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
}
}
愛華網(wǎng)



