用的是windows自帶的dll包,沒有引用第三方文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-718006.html
1?WordHelper.cs
using System;
using Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
namespace cadWord
{
public class WordHelper
{
private Microsoft.Office.Interop.Word.Document wDoc = null;
private Microsoft.Office.Interop.Word.Application wApp = null;
public Microsoft.Office.Interop.Word.Document Document
{
get { return wDoc; }
set { wDoc = value; }
}
public Microsoft.Office.Interop.Word.Application Application
{
get { return wApp; }
set { wApp = value; }
}
/// <summary>
/// 打開指定WORD文檔
/// </summary>
/// <param name="strFileName"></param>
public void Open(string strFileName)
{
wApp = new Microsoft.Office.Interop.Word.ApplicationClass();
object fileName = strFileName;
object readOnly = false;
object isVisible = true;
object missing = Type.Missing;
wDoc = wApp.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);
wDoc.Activate();
}
#region 從模板創(chuàng)建新的Word文檔
/// <summary>
/// 從模板創(chuàng)建新的Word文檔
/// </summary>
/// <param name="templateName">模板文件名</param>
/// <returns></returns>
public bool CreateNewWordDocument(string templateName)
{
try
{
return CreateNewWordDocument(templateName, ref wDoc, ref wApp);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region 從模板創(chuàng)建新的Word文檔,并且返回對(duì)象Document,Application
/// <summary>
/// 從模板創(chuàng)建新的Word文檔,
/// </summary>
/// <param name="templateName">模板文件名</param>
/// <param name="wDoc">返回的Word.Document對(duì)象</param>
/// <param name="WApp">返回的Word.Application對(duì)象</param>
/// <returns></returns>
public static bool CreateNewWordDocument(string templateName, ref Microsoft.Office.Interop.Word.Document wDoc, ref Microsoft.Office.Interop.Word.Application WApp)
{
Microsoft.Office.Interop.Word.Document thisDocument = null;
Microsoft.Office.Interop.Word.Application thisApplication = new Microsoft.Office.Interop.Word.Application();/
thisApplication.Visible = false;
thisApplication.Caption = "";
thisApplication.Options.CheckSpellingAsYouType = false;
thisApplication.Options.CheckGrammarAsYouType = false;
Object Template = templateName;// Optional Object. The name of the template to be used for the new document. If this argument is omitted, the Normal template is used.
Object NewTemplate = false;// Optional Object. True to open the document as a template. The default value is False.
Object DocumentType = Microsoft.Office.Interop.Word.WdNewDocumentType.wdNewBlankDocument; // Optional Object. Can be one of the following WdNewDocumentType constants: wdNewBlankDocument, wdNewEmailMessage, wdNewFrameset, or wdNewWebPage. The default constant is wdNewBlankDocument.
Object Visible = true;//Optional Object. True to open the document in a visible window. If this value is False, Microsoft Word opens the document but sets the Visible property of the document window to False. The default value is True.
try
{
Microsoft.Office.Interop.Word.Document wordDoc = thisApplication.Documents.Add(ref Template, ref NewTemplate, ref DocumentType, ref Visible);
thisDocument = wordDoc;
wDoc = wordDoc;
WApp = thisApplication;
return true;
}
catch (Exception ex)
{
string err = string.Format("創(chuàng)建Word文檔出錯(cuò),錯(cuò)誤原因:{0}", ex.Message);
throw new Exception(err, ex);
}
}
#endregion
#region 文檔另存為其他文件名
/// <summary>
/// 文檔另存為其他文件名
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="wDoc">Document對(duì)象</param>
public bool SaveAs(string fileName)
{
try
{
return SaveAs(fileName, wDoc);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region 文檔另存為其他文件名
/// <summary>
/// 文檔另存為其他文件名
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="wDoc">Document對(duì)象</param>
public static bool SaveAs(string fileName, Microsoft.Office.Interop.Word.Document wDoc)
{
Object FileName = fileName; // 文檔的名稱。默認(rèn)值是當(dāng)前文件夾名和文件名。如果文檔在以前沒有保存過,則使用默認(rèn)名稱(例如,Doc1.doc)。如果已經(jīng)存在具有指定文件名的文檔,則會(huì)在不先提示用戶的情況下改寫文檔。
Object FileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument; // 文檔的保存格式。可以是任何 WdSaveFormat 值。要以另一種格式保存文檔,請(qǐng)為 SaveFormat 屬性指定適當(dāng)?shù)闹怠?
Object LockComments = false; // 如果為 true,則鎖定文檔以進(jìn)行注釋。默認(rèn)值為 false。
Object Password = System.Type.Missing; // 用來(lái)打開文檔的密碼字符串。(請(qǐng)參見下面的備注。)
Object AddToRecentFiles = false; // 如果為 true,則將該文檔添加到“文件”菜單上最近使用的文件列表中。默認(rèn)值為 true。
Object WritePassword = System.Type.Missing; // 用來(lái)保存對(duì)文件所做更改的密碼字符串。(請(qǐng)參見下面的備注。)
Object ReadOnlyRecommended = false; // 如果為 true,則讓 Microsoft Office Word 在打開文檔時(shí)建議只讀狀態(tài)。默認(rèn)值為 false。
Object EmbedTrueTypeFonts = false; //如果為 true,則將 TrueType 字體隨文檔一起保存。如果省略的話,則 EmbedTrueTypeFonts 參數(shù)假定 EmbedTrueTypeFonts 屬性的值。
Object SaveNativePictureFormat = true; // 如果圖形是從另一個(gè)平臺(tái)(例如,Macintosh)導(dǎo)入的,則 true 表示僅保存導(dǎo)入圖形的 Windows 版本。
Object SaveFormsData = false; // 如果為 true,則將用戶在窗體中輸入的數(shù)據(jù)另存為數(shù)據(jù)記錄。
Object SaveAsAOCELetter = false; // 如果文檔附加了郵件程序,則 true 表示會(huì)將文檔另存為 AOCE 信函(郵件程序會(huì)進(jìn)行保存)。
Object Encoding = System.Type.Missing; // MsoEncoding。要用于另存為編碼文本文件的文檔的代碼頁(yè)或字符集。默認(rèn)值是系統(tǒng)代碼頁(yè)。
Object InsertLineBreaks = true; // 如果文檔另存為文本文件,則 true 表示在每行文本末尾插入分行符。
Object AllowSubstitutions = false; //如果文檔另存為文本文件,則 true 允許 Word 將某些符號(hào)替換為外觀與之類似的文本。例如,將版權(quán)符號(hào)顯示為 (c)。默認(rèn)值為 false。
Object LineEnding = Microsoft.Office.Interop.Word.WdLineEndingType.wdCRLF;// Word 在另存為文本文件的文檔中標(biāo)記分行符和換段符??梢允侨魏?WdLineEndingType 值。
Object AddBiDiMarks = true;//如果為 true,則向輸出文件添加控制字符,以便保留原始文檔中文本的雙向布局。
try
{
wDoc.SaveAs(ref FileName, ref FileFormat, ref LockComments, ref Password, ref AddToRecentFiles, ref WritePassword
, ref ReadOnlyRecommended, ref EmbedTrueTypeFonts, ref SaveNativePictureFormat
, ref SaveFormsData, ref SaveAsAOCELetter, ref Encoding, ref InsertLineBreaks, ref AllowSubstitutions
, ref LineEnding, ref AddBiDiMarks);
return true;
}
catch (Exception ex)
{
string err = string.Format("另存文件出錯(cuò),錯(cuò)誤原因:{0}", ex.Message);
throw new Exception(err, ex);
}
}
#endregion
#region 關(guān)閉文檔
/// <summary>
/// 關(guān)閉文檔
/// </summary>
public void Close()
{
Close(wDoc, wApp);
wDoc = null;
wApp = null;
}
#endregion
[DllImport("shell32.dll ")]
public static extern int ShellExecute(IntPtr hwnd, String lpszOp, String lpszFile, String lpszParams, String lpszDir, int FsShowCmd);
#region 關(guān)閉文檔
/// <summary>
/// 關(guān)閉文檔
/// </summary>
/// <param name="wDoc">Document對(duì)象</param>
/// <param name="WApp">Application對(duì)象</param>
public static void Close(Microsoft.Office.Interop.Word.Document wDoc, Microsoft.Office.Interop.Word.Application WApp)
{
Object SaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdSaveChanges;// 指定文檔的保存操作??梢允窍铝?WdSaveOptions 值之一:wdDoNotSaveChanges、wdPromptToSaveChanges 或 wdSaveChanges。
Object OriginalFormat = Microsoft.Office.Interop.Word.WdOriginalFormat.wdOriginalDocumentFormat;// 指定文檔的保存格式??梢允窍铝?WdOriginalFormat 值之一:wdOriginalDocumentFormat、wdPromptUser 或 wdWordDocument。
Object RouteDocument = false;// 如果為 true,則將文檔傳送給下一個(gè)收件人。如果沒有為文檔附加傳送名單,則忽略此參數(shù)。
try
{
if (wDoc != null) wDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
if (WApp != null) WApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region 填充書簽
/// <summary>
/// 填充書簽
/// </summary>
/// <param name="bookmark">書簽</param>
/// <param name="value">值</param>
public void Replace(string bookmark, string value)
{
try
{
object bkObj = bookmark;
if (wApp.ActiveDocument.Bookmarks.Exists(bookmark) == true)
{
wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
}
else return;
wApp.Selection.TypeText(value);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
public bool FindTable(string bookmarkTable)
{
try
{
object bkObj = bookmarkTable;
if (wApp.ActiveDocument.Bookmarks.Exists(bookmarkTable) == true)
{
wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
return true;
}
else
return false;
}
catch (Exception ex)
{
throw ex;
}
}
public void MoveNextCell()
{
try
{
Object unit = Microsoft.Office.Interop.Word.WdUnits.wdCell;
Object count = 1;
wApp.Selection.Move(ref unit, ref count);
}
catch (Exception ex)
{
throw ex;
}
}
public void tableInsertRows(int i, int j, int count, int k)
{
Microsoft.Office.Interop.Word.Table newTable = wDoc.Tables[k];
for (int jj = 0; jj < count; jj++)
{
object beforeRow = newTable.Cell(i, j).Range;
newTable.Rows.Add(ref beforeRow);
}
}
public void SetWordCellValue(int i, int j, int k, string value)
{
try
{
Microsoft.Office.Interop.Word.Table newTable = wDoc.Tables[k];
newTable.Cell(i, j).Range.Text = value;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 插入圖片
/// </summary>
/// <param name="i"></param>
/// <param name="j"></param>
/// <param name="k"></param>
/// <param name="strPicPath"></param>
public void InsertImage(int i, int j, int k, string strPicPath)
{
Microsoft.Office.Interop.Word.Table newTable = wDoc.Tables[k];
string FileName = strPicPath;
object LinkToFile = false;
object SaveWithDocument = true;
object Anchor = newTable.Cell(i, j).Range;
wApp.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor).Select();
}
public void SetCellValue(string value)
{
try
{
wApp.Selection.Rows.Alignment = WdRowAlignment.wdAlignRowCenter;
wApp.Selection.TypeText(value);
wApp.Selection.Rows.Alignment = WdRowAlignment.wdAlignRowCenter;
}
catch (Exception ex)
{
throw ex;
}
}
public string GetCellValue()
{
try
{
string value = wApp.Selection.Text;
if (value.Length <= 2)
{
return "";
}
else
return value;
}
catch (Exception ex)
{
throw ex;
}
}
public void MoveNextRow()
{
try
{
Object extend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
Object unit = Microsoft.Office.Interop.Word.WdUnits.wdCell;
Object count = 1;
wApp.Selection.MoveRight(ref unit, ref count, ref extend);
}
catch (Exception ex)
{
throw ex;
}
}
//獲取word文件的文本內(nèi)容
public string DocToText(string docFileName, out Font xx)
{
//實(shí)例化COM
Application Word_App = new Application();/
object fileobj = docFileName;
object nullobj = System.Reflection.Missing.Value;//打開指定文件(不同版本的COM參數(shù)個(gè)數(shù)有差異,
//一般而言除第一個(gè)外都用nullobj就行了)
Document wd = Word_App.Documents.Open(ref fileobj, ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj);
//取得doc文件中的文本內(nèi)容
string outText = wd.Content.Text;
xx = wd.Content.Font;
//關(guān)閉文件
wd.Close(ref nullobj, ref nullobj, ref nullobj);
//關(guān)閉COM
Word_App.Quit(ref nullobj, ref nullobj, ref nullobj);
//返回文本內(nèi)容
return outText;
}
/// <summary>
/// 復(fù)制模板中已經(jīng)存放的表,并生成其后位置不定數(shù)量的表
/// </summary>
/// <param name="_tableIndex">對(duì)象表</param>
/// <param name="_row">表后位置,即計(jì)算其行列數(shù)也能得出數(shù)字</param>
/// <param name="_tableNum">表數(shù)量</param>
public void copyTableInsert(int _tableIndex, object _row, int _tableNum)
{
//--start-#根據(jù)表序號(hào)索引,獲取對(duì)象表#-->
Microsoft.Office.Interop.Word.Table copyTable = wDoc.Tables[_tableIndex];
//--start-#復(fù)制該對(duì)象表#-->
copyTable.Range.Copy();//復(fù)制一下
//--start-#讓光標(biāo)選中該對(duì)象表#-->
copyTable.Select();
//--start-#不允許表跨頁(yè)斷行#-->
copyTable.AllowPageBreaks = false;
object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToLine;
object which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToNext;
object missing = Type.Missing;
//--start-#讓光標(biāo)移至表后#-->
wApp.Selection.GoTo(ref what, ref which, ref _row, ref missing);
//--start-#計(jì)算生成的表數(shù)量#-->
for (int i = 0; i < _tableNum; i++)
{
//--start-#表后插入分頁(yè)符#-->
wApp.Selection.InsertBreak(ref missing);
//--start-#復(fù)制表生成#-->
wApp.Selection.Paste();
}
// Microsoft.Office.Interop.Word.Table copyTable = wDoc.Tables[3];
// copyTable.Range.Copy();//復(fù)制一下
// copyTable.Select();//選中表對(duì)象,此時(shí)光標(biāo)已經(jīng)在這張表格上了
// copyTable.AllowPageBreaks = false;
// //復(fù)制后的第一張表:實(shí)驗(yàn)室2
// object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToLine;
// object which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToNext;
// object missing = Type.Missing;
// // object count = 36;//光標(biāo)下移3格
// wApp.Selection.GoTo(ref what, ref which, ref _row, ref missing);
// // wApp.Selection.Range.Text = "單體建筑核實(shí)比對(duì)表2\n";//插入文本
// wApp.Selection.GoTo(ref what, ref which, 1, ref missing);//光標(biāo)下移1格,不和被測(cè)科室這個(gè)文本在一塊,另起一行
// wApp.Selection.Paste();//粘貼表
// //復(fù)制后的第一張表:實(shí)驗(yàn)室2
// //what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToLine;
// //which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToNext;
wApp.Selection.Range.Text = "被測(cè)科室:實(shí)驗(yàn)室2\n";//插入文本
// wApp.Selection.GoTo(ref what, ref which, 1, ref missing);//光標(biāo)下移1格,不和被測(cè)科室這個(gè)文本在一塊,另起一行
// wApp.Selection.Paste();//粘貼表
}
}
}
2 核心代碼
/// <summary>
/// 復(fù)制模板中已經(jīng)存放的表,并生成其后位置不定數(shù)量的表
/// </summary>
/// <param name="_tableIndex">對(duì)象表</param>
/// <param name="_row">表后位置,即計(jì)算其行列數(shù)也能得出數(shù)字</param>
/// <param name="_tableNum">表數(shù)量</param>
public void copyTableInsert(int _tableIndex, object _row, int _tableNum)
{
//--start-#根據(jù)表序號(hào)索引,獲取對(duì)象表#-->
Microsoft.Office.Interop.Word.Table copyTable = wDoc.Tables[_tableIndex];
//--start-#復(fù)制該對(duì)象表#-->
copyTable.Range.Copy();//復(fù)制一下
//--start-#讓光標(biāo)選中該對(duì)象表#-->
copyTable.Select();
//--start-#不允許表跨頁(yè)斷行#-->
copyTable.AllowPageBreaks = false;
object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToLine;
object which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToNext;
object missing = Type.Missing;
//--start-#讓光標(biāo)移至表后#-->
wApp.Selection.GoTo(ref what, ref which, ref _row, ref missing);
//--start-#計(jì)算生成的表數(shù)量#-->
for (int i = 0; i < _tableNum; i++)
{
//--start-#表后插入分頁(yè)符#-->
wApp.Selection.InsertBreak(ref missing);
//--start-#復(fù)制表生成#-->
wApp.Selection.Paste();
}
// Microsoft.Office.Interop.Word.Table copyTable = wDoc.Tables[3];
// copyTable.Range.Copy();//復(fù)制一下
// copyTable.Select();//選中表對(duì)象,此時(shí)光標(biāo)已經(jīng)在這張表格上了
// copyTable.AllowPageBreaks = false;
// //復(fù)制后的第一張表:實(shí)驗(yàn)室2
// object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToLine;
// object which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToNext;
// object missing = Type.Missing;
// // object count = 36;//光標(biāo)下移3格
// wApp.Selection.GoTo(ref what, ref which, ref _row, ref missing);
// // wApp.Selection.Range.Text = "單體建筑核實(shí)比對(duì)表2\n";//插入文本
// wApp.Selection.GoTo(ref what, ref which, 1, ref missing);//光標(biāo)下移1格,不和被測(cè)科室這個(gè)文本在一塊,另起一行
// wApp.Selection.Paste();//粘貼表
// //復(fù)制后的第一張表:實(shí)驗(yàn)室2
// //what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToLine;
// //which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToNext;
wApp.Selection.Range.Text = "被測(cè)科室:實(shí)驗(yàn)室2\n";//插入文本
// wApp.Selection.GoTo(ref what, ref which, 1, ref missing);//光標(biāo)下移1格,不和被測(cè)科室這個(gè)文本在一塊,另起一行
// wApp.Selection.Paste();//粘貼表
}
3 調(diào)用代碼
批量插入表格后,原理就是整個(gè)文檔會(huì)從前到后編制表格索引,從一開始意思是前面序號(hào)為1.2.3表格,1復(fù)制3個(gè)在后面,那么原先的2表格序號(hào)就標(biāo)為2+3=5!為表格設(shè)置各種值也是按這個(gè)序號(hào)來(lái)!文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-718006.html
private void button1_Click(object sender, EventArgs e)
{
string mbPath = System.IO.Path.Combine(Application.StartupPath + "\\MB", "測(cè)量報(bào)告樣本.docx");//模板
string savePath = @"C:\Users\54061\Desktop\333\test\測(cè)量報(bào)告樣本.docx";//保存路徑
//string imagePath = @"C:\Users\54061\Desktop\彭澤軍\test\江西省工程有限公司(公章).png";//保存路徑
File.Copy(mbPath, savePath, true);
WordHelper wordhelper = new WordHelper();
wordhelper.Open(savePath);
//--start-#計(jì)算生成的表#-->
wordhelper.copyTableInsert(3, 32, 5);
wordhelper.copyTableInsert(4 + 5, 4, 5);
wordhelper.copyTableInsert(5 + 5 + 5, 14, 5);
//--start-#計(jì)算單體建筑核實(shí)比對(duì)表#-->
wordhelper.Close();
MessageBox.Show("導(dǎo)出完成!");
}
到了這里,關(guān)于c# 操作word中的表格 批量復(fù)制和批量插入的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!