添加现有文件,DocManager.cs
在原文件的基础上新添加了:
1、设置单元格的边框样式
2、设置表格行、列的边框样
3、单元格内容垂直居中、靠上、靠下
4、按行合并单元格
5、按列合并单元格
---------------------------------------------------文件内容---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word;
using System.Data;
namespace FluidDesign
{
///
/// IDocManager 接口。
///
public interface IDocManager
{
///
/// 返回WORD对象
///
Word.Application Application
{
get;
}
///
/// 返回DOC对象
///
Word.Document Document
{
get;
}
///
/// 新建空白文档
///
void Add();
///
/// 从模板文件中新建文档
///
/// 模板文件路径及文件名
void Add(string templateFileName);
///
/// 以只读的方式从模板文件中新建文档
///
void AddByReadOnly(string TemplateFileName);
///
/// 打开WORD文件
///
/// 文件名
void Open(string fileName);
///
/// 以只读的方式打开WORD文件
///
/// 文件名
void Open(string fileName, bool isReadOnly);
///
/// 当前文档章节数,包含空行了章节数,行数,页数,段落数,字数
///
///
string[] GetFileInfo();
///
/// 在文档空白的地方添加文字内容
///
/// 文本内容
void AppendText(string wordText);
///
/// 插入空行
///
void InsertBlankLine();
///
/// 插入指定行数的空行
///
/// 行数
void InsertBlankLine(int lineNumber);
///
/// 添加分页符
///
void InsertPageBreak();
///
/// 插入表格
///
/// 表格数据
void InsertTable(ref System.Data.DataTable table);
///
/// 设置表格的边界样式
///
///
///
void SetTableBorderStyle(int itable, Word.WdLineStyle LineStyle);
///
/// 设置单元格边界样式
///
///
void SetCellBorderStyle(int itable, int row, int col, Word.WdBorderType WdBorderType, Word.WdLineStyle LineStyle);
/// 设置表格行边界样式
///
///
///
void SetRowBorderStyle(int itable, int row, Word.WdBorderType WdBorderType, Word.WdLineStyle LineStyle);
///
/// 设置表格列边界样式
///
///
void SetColBorderStyle(int itable, int col, Word.WdBorderType WdBorderType, Word.WdLineStyle LineStyle);
///
/// 设置表格的字体大小
///
///
///
void SetTableFontSize(int itable, float Size);
///
/// 设置单元格字体对齐方式,垂直,靠上
///
///
void SetCellAlignmentStyle(int itable, int row, int col, Word.WdCellVerticalAlignment wdVerticalAlignment);
//合并单元格 从第RowIndex行 ,第ColumnIndex列的单元格开始,合并Length个单元格
void MergeColumCell(int itable, int RowIndex, int ColumnIndex, int Lenght);
//按行合并单元格 从第RowIndex行 ,第ColumnIndex列的单元格开始,合并Length个单元格
void MergeRowCell(int itable, int RowIndex, int ColumnIndex, int Lenght);
///
/// 设置页眉
///
/// 放置的文本
void SetPageHeader(string text);
///
/// 设置页脚
///
/// 放置的文本
void SetPageFooter(string text);
///
/// 设定对齐
///
/// 对齐方式
void SetAlignment(string alignmentType);
///
/// 设置字体名称
///
/// 字体名称
void SetFontName(string fontName);
///
/// 设置字体风格
///
/// 字体风格
void SetFontStyle(string fontStyle);
///
/// 取消字体风格
///
void DisabledFontStyle();
///
/// 设定字号
///
/// 字号
void SetFontSize(int size);
///
/// 设置颜色
///
///
void SetFontColor(Word.WdColor color);
///
/// 选择段落文本
///
/// 段落
void SelectRange(int para);
///
/// 选择页眉
///
void SelectPageHeader();
///
/// 选择页脚
///
void SelectPageFooter();
///
/// 设置页面切换到主页面
///
void SetDocSeekViewToMainDocument();
///
/// 选择文本
///
/// 段落
/// 句子
void SelectRange(int para, int sentences);
///
/// 选择文本
///
/// 开始处
/// 结束处
void SelectRange(long start, long end);
///
/// 转到书签
///
/// 书签名称
void FindBookMark(string bookMark);
///
/// 判断书签是否存在
///
/// 书签名称
///
bool BookMarkExists(string bookMark);
///
/// 修改标签内容
///
void setRangleText(Word.Bookmark bm, string text);
///
/// 转到文档开头
///
void GotoDocBegin();
///
/// 转到文档结尾
///
void GotoDocEnd();
///
/// 转到表格
///
///
void GoToTheTable(int ntable);
///
/// 转到某个表格的某个单元格
///
/// 表格序号
/// 行号
/// 列号
void GotoTableCell(int nTable, int nRow, int nColumn);
///
/// 某个表格的某个单元格的值
///
///
///
///
///
string GetTableCellValue(int nTable, int nRow, int nColumn);
///
/// 转到右边单元格
///
void GoToRightCell();
///
/// 转到左边单元格
///
void GoToLeftCell();
///
/// 表格中转到下面的单元格
///
void GoToDownCell();
///
/// 表格中转到上面的单元格
///
void GoToUpCell();
///
/// 插入图片到WORD文档中
///
///
void InsertPicture(string FileName);
///
/// 插入WORD文件
///
/// 文件名称
void InsertWordFile(string fileName);
///
/// 填充单元格
///
/// 文件名称
void FillRow(int itable, int Row, int Cell, string str);
///
/// 添加单元格
///
/// 表格索引
/// /// 生成多少行
void AddRow(int itable,int irow);
///
/// 另存文件
///
///
void SavaAs(object path);
///
/// 删除文件
///
/// 文件名
void FileDelete(string absoluteFilePath);
///
/// 杀除所有WINWORD进程
///
void KillWinWord();
///
/// 关闭文档
///
void CloseWordAndDoc();
///
/// 添加文体
///
/// 文本
/// 字体
/// 大小
/// 风格
void AppendText(string WordText, string font, int size, string bold);
/**/
///
/// 段落的对齐方式
/// 例如:word.SetAlignment(Word.WdParagraphAlignment.wdAlignParagraphCenter)
///
///
// void SetAlignment(Word.WdParagraphAlignment alignment);
///
/// 首行缩进
///
/// float类型的数值
void SetFirstLineIndent(float fltCount);
///
/// 左缩进
///
/// float类型的数值
void SetLeftIndent(float fltCount);
///
/// 右缩进
///
/// float类型的数值
void SetRightIndent(float fltCount);
///
/// 行距
///
///
void SetLineSpacingRule(int spacePoint);
///
/// 段后据
///
///
void SetSpaceAfter(float space);
///
/// 段前据
///
///
void SetSpaceBefore(float space);
///
/// 标题级别
///
/// 标题级别
void InsertParaTitle(int level);
///
/// 更新目录
///
void UpdateCatagory(float fontsize);
}
public class DocManager : IDocManager
{
///
/// 页面方向
///
///
#region 变量声明
public enum Orientation
{
Landscape,//横向
Portrait//纵向
}
public Word.Application _oWord;
public Word.Document _oDoc = null;
private object _oMissing = System.Reflection.Missing.Value;
private bool _IsDispose = false;
///
/// 页面方式
///
///
private Orientation _setorientation = Orientation.Portrait;
#endregion
#region 初始化
public DocManager()
{
try
{
_oWord = new Word.Application();
}
catch{
}
}
///
/// 垃圾回收
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
///
/// 添对象
///
///
private void NAR(object o)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
}
catch {}
finally
{
o = null;
}
}
///
/// 释放资源
///
///
protected virtual void Dispose(bool disposing)
{
if(!this._IsDispose)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
if(_oDoc != null)
_oDoc.Close(ref _oMissing,ref _oMissing,ref _oMissing);
if(_oWord != null)
_oWord.Application.Quit(ref _oMissing,ref _oMissing,ref _oMissing);
if(_oDoc != null)
NAR(_oDoc);
if(_oWord != null)
NAR(_oWord);
_oDoc = null;
_oWord = null;
GC.Collect();
}
}
_IsDispose = true;
}
~DocManager()
{
Dispose(false);
}
///
/// 返回DOC对象
///
public Word.Document Document
{
get
{
return this._oDoc;
}
}
///
/// 返回WORD对象
///
public Word.Application Application
{
get
{
return this._oWord;
}
}
#endregion
#region 新建和打开文件
///
/// 新建空白文档
///
public void Add()
{
Word.Documents _oDocs = _oWord.Documents;
_oDoc = _oDocs.Add(ref _oMissing, ref _oMissing, ref _oMissing, ref _oMissing);
if (Orientation.Landscape == _setorientation) //横向
{
_oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
}
NAR(_oDocs);
}
///
/// 从模板文件中新建文档
///
public void Add(string TemplateFileName)
{
Word.Documents _oDocs = _oWord.Documents;
object fileName = TemplateFileName;
_oDoc = _oDocs.Add(ref fileName, ref _oMissing, ref _oMissing, ref _oMissing);
_oDoc.Activate();
if(Orientation.Landscape == _setorientation) //横向
{
_oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
}
NAR(_oDocs);
_oWord.Visible = true;
}
///
/// 以只读的方式从模板文件中新建文档
///
public void AddByReadOnly(string TemplateFileName)
{
object fileName = TemplateFileName;
object readOnly = true;
object isVisible = true;
Word.Documents _oDocs = _oWord.Documents;
_oDoc = _oDocs.Open(ref fileName, ref _oMissing, ref readOnly, ref _oMissing,
ref _oMissing, ref _oMissing, ref _oMissing, ref _oMissing, ref _oMissing,
ref _oMissing, ref _oMissing, ref isVisible, ref _oMissing, ref _oMissing,
ref _oMissing, ref _oMissing);
_oDoc.Activate();
if (Orientation.Landscape == _setorientation) //横向
{
_oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
}
NAR(_oDocs);
_oWord.Visible = true;
}
///
/// 打开WORD文件
///
/// 文件名
public void Open(string FileName)
{
object fileName = FileName;
object readOnly = false;
object isVisible = true;
try
{
Word.Documents _oDocs = _oWord.Documents;
//打开文档
_oDoc = _oDocs.Open(ref fileName, ref _oMissing, ref readOnly, ref _oMissing,
ref _oMissing, ref _oMissing, ref _oMissing, ref _oMissing, ref _oMissing,
ref _oMissing, ref _oMissing, ref isVisible, ref _oMissing, ref _oMissing,
ref _oMissing, ref _oMissing);
//激活文档
_oDoc.Activate();
NAR(_oDocs);
}
catch
{
//发生错误
}
finally
{
this.Dispose();
//_oWord.Application.Quit(ref _oMissing,ref _oMissing,ref _oMissing);
}
}
///
/// 以只读的方式打开WORD文件
///
/// 文件名
public void Open(string FileName, bool IsReadOnly)
{
object fileName = FileName;
object readOnly = IsReadOnly;
object isVisible = true;
try
{
Word.Documents _oDocs = _oWord.Documents;
//打开文档
_oDoc = _oDocs.Open(ref fileName, ref _oMissing, ref readOnly, ref _oMissing,
ref _oMissing, ref _oMissing, ref _oMissing, ref _oMissing, ref _oMissing,
ref _oMissing, ref _oMissing, ref isVisible, ref _oMissing, ref _oMissing,
ref _oMissing, ref _oMissing);
//激活文档
_oDoc.Activate();
NAR(_oDocs);
}
catch
{
//发生错误
}
finally
{
this.Dispose();
//_oWord.Application.Quit(ref _oMissing,ref _oMissing,ref _oMissing);
}
}
#endregion
#region 内容操作
///
/// 删除选择的内容
///
public void Clear()
{
//_oDoc.Paragraphs.Last.Range.Text = WordText;
_oWord.Selection.Delete(ref _oMissing, ref _oMissing);
}
///
/// 在文档空白的地方添加文字内容
///
/// 文本内容
public void AppendText(string WordText,string font,int size,string bold)
{
//_oDoc.Paragraphs.Last.Range.Text = WordText;
SetFontSize(size);
SetFontStyle(bold);
SetFontName(font);
_oWord.Selection.TypeText(WordText);
DisabledFontStyle();
}
public void AppendText(string WordText)
{
//_oDoc.Paragraphs.Last.Range.Text = WordText;
_oWord.Selection.TypeText(WordText);
}
///
/// 替换文本
///
///
public void ReplaceText(string WordText)
{
//_oDoc.Paragraphs.Last.Range.Text = WordText;
_oWord.Options.ReplaceSelection = true;
_oWord.Selection.TypeText(WordText);
_oWord.Options.ReplaceSelection = false;
}
///
/// 插入空行
///
public void InsertBlankLine()
{
_oWord.Selection.TypeParagraph();
}
///
/// 插入指定行数的空行
///
/// 行数
public void InsertBlankLine(int LineNumber)
{
for (int i = 0; i < LineNumber; i++)
_oWord.Selection.TypeParagraph();
}
///
/// 添加分页符
///
public void InsertPageBreak()
{
object pageBreak = (int)Word.WdBreakType.wdPageBreak;
_oWord.Selection.InsertBreak(ref pageBreak);
}
///
/// 修改标签内容
///
public void setRangleText(Word.Bookmark bm, string text)
{
bm.Select();
bm.Range.Text = text=="-1"?"":text;
}
///
/// 插入表格
///
/// 表格数据
///
public void InsertTable(ref DataTable table)
{
Word.Table oTable;
int rowIndex = 1, colIndex = 0;
int rowsNumber, columnsNumber;
rowsNumber = table.Rows.Count + 1;
columnsNumber = table.Columns.Count;
oTable = _oDoc.Tables.Add(_oWord.Selection.Range, rowsNumber, columnsNumber, ref _oMissing, ref _oMissing);
//初始化列
foreach (DataColumn Col in table.Columns)
{
colIndex += 1;
oTable.Cell(1, colIndex).Range.InsertAfter(Col.ColumnName);
}
//添加行
foreach (DataRow Row in table.Rows)
{
rowIndex += 1;
colIndex = 0;
//按列添加
foreach (DataColumn Col in table.Columns)
{
colIndex += 1;
oTable.Cell(rowIndex, colIndex).Range.InsertAfter(Row[Col.ColumnName].ToString());
}
}
oTable.AllowAutoFit = true;
oTable.ApplyStyleFirstColumn = true;
oTable.ApplyStyleHeadingRows = true;
}
///
/// 设置表格行边界样式
///
///
public void SetRowBorderStyle(int itable, int row, Word.WdBorderType WdBorderType, Word.WdLineStyle LineStyle)
{
_oDoc.Tables[itable].Rows[row].Borders[WdBorderType].LineStyle = LineStyle;
}
///
/// 设置表格列边界样式
///
///
public void SetColBorderStyle(int itable, int col, Word.WdBorderType WdBorderType, Word.WdLineStyle LineStyle)
{
_oDoc.Tables[itable].Columns[col].Borders[WdBorderType].LineStyle = LineStyle;
}
///
///
/// 设置单元格边界样式
///
///
public void SetCellBorderStyle(int itable,int row,int col,Word.WdBorderType WdBorderType, Word.WdLineStyle LineStyle)
{
_oDoc.Tables[itable].Rows[row].Cells[col].Borders[WdBorderType].LineStyle = LineStyle;
}
///
/// 设置表格边界样式
///
///
public void SetTableBorderStyle(int itable,Word.WdLineStyle LineStyle)
{
_oDoc.Tables[itable].Borders[Word.WdBorderType.wdBorderTop].LineStyle=LineStyle;
_oDoc.Tables[itable].Borders[Word.WdBorderType.wdBorderLeft ].LineStyle = LineStyle;
_oDoc.Tables[itable].Borders[Word.WdBorderType.wdBorderRight ].LineStyle = LineStyle;
_oDoc.Tables[itable].Borders[Word.WdBorderType.wdBorderBottom ].LineStyle = LineStyle;
_oDoc.Tables[itable].Borders[Word.WdBorderType.wdBorderHorizontal ].LineStyle = LineStyle;
_oDoc.Tables[itable].Borders[Word.WdBorderType.wdBorderVertical ].LineStyle = LineStyle;
}
///
/// 设置单元格字体对齐方式,垂直,靠上
///
///
public void SetCellAlignmentStyle(int itable, int row, int col, Word.WdCellVerticalAlignment wdVerticalAlignment)
{
_oDoc.Tables[itable].Rows[row].Cells[col].VerticalAlignment = wdVerticalAlignment;
}
///
/// 设置表格的字体大小
///
///
///
public void SetTableFontSize(int itable, float Size)
{
_oDoc.Tables[itable].Range.Font.Size = Size;
}
//按列合并单元格 从第RowIndex行 ,第ColumnIndex列的单元格开始,合并Length个单元格
public void MergeColumCell(int itable,int RowIndex,int ColumnIndex, int Lenght)
{
//or(int index=1;index<=Lenght;index++)
{
_oDoc.Tables[itable].Cell(RowIndex, ColumnIndex).Merge(_oDoc.Tables[itable].Cell(RowIndex + Lenght, ColumnIndex));
}
}
//按行合并单元格 从第RowIndex行 ,第ColumnIndex列的单元格开始,合并Length个单元格
public void MergeRowCell(int itable, int RowIndex, int ColumnIndex, int Lenght)
{
// for (int index = 1; index <= Lenght; index++)
{
_oDoc.Tables[itable].Cell(RowIndex, ColumnIndex).Merge(_oDoc.Tables[itable].Cell(RowIndex, ColumnIndex + Lenght));
}
}
///
/// 填充单元格
///
/// 表格行数
/// 第一行单元格数目
/// 文档中的表格索引号
public void FillRow(int itable,int Row, int Cell,string str)
{
_oDoc.Tables[itable].Cell(Row, Cell).Range.InsertAfter(str);
}
///
/// 添加单元格
///
/// 文档中的表格索引号
public void AddRow(int itable,int irow)
{
for (int i = 1; i <= irow; i++)
{
_oDoc.Tables[itable].Rows.Add(ref _oMissing);
}
}
#endregion
#region 得到当前文件信息
///
/// 当前文档章节数,包含空行了章节数,行数,页数,段落数,字数
///
///
public string[] GetFileInfo()
{
string[] FileInfo = new string[6];//章节数,包含空行了章节数,行数,页数,段落数,字数;
object IncludeFootnotesAndEndnotes = false;
FileInfo[0] = _oDoc.ComputeStatistics(Word.WdStatistic.wdStatisticCharacters, ref IncludeFootnotesAndEndnotes).ToString();
FileInfo[1] = _oDoc.ComputeStatistics(Word.WdStatistic.wdStatisticCharactersWithSpaces, ref IncludeFootnotesAndEndnotes).ToString();
FileInfo[2] = _oDoc.ComputeStatistics(Word.WdStatistic.wdStatisticLines, ref IncludeFootnotesAndEndnotes).ToString();
FileInfo[3] = _oDoc.ComputeStatistics(Word.WdStatistic.wdStatisticPages, ref IncludeFootnotesAndEndnotes).ToString();
FileInfo[4] = _oDoc.ComputeStatistics(Word.WdStatistic.wdStatisticParagraphs, ref IncludeFootnotesAndEndnotes).ToString();
FileInfo[5] = _oDoc.ComputeStatistics(Word.WdStatistic.wdStatisticWords, ref IncludeFootnotesAndEndnotes).ToString();
return FileInfo;
}
#endregion
#region 设置
///
/// 设置页眉
///
/// 放置的文本
public void SetPageHeader(string text)
{
if (_oWord.ActiveWindow.View.SplitSpecial != Word.WdSpecialPane.wdPaneNone)
_oWord.ActiveWindow.Panes[2].Close();
if (_oWord.ActiveWindow.View.Type == Word.WdViewType.wdNormalView || _oWord.ActiveWindow.View.Type == Word.WdViewType.wdOutlineView)
_oWord.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdPrintView;
_oWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekPrimaryHeader;
this.GotoDocEnd();
this.AppendText(text, "黑体", 9, "plain");
_oWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
}
///
/// 设置页脚
///
/// 放置的文本
public void SetPageFooter(string text)
{
if (_oWord.ActiveWindow.View.SplitSpecial != Word.WdSpecialPane.wdPaneNone)
_oWord.ActiveWindow.Panes[2].Close();
if (_oWord.ActiveWindow.View.Type == Word.WdViewType.wdNormalView || _oWord.ActiveWindow.View.Type == Word.WdViewType.wdOutlineView)
_oWord.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdPrintView;
_oWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekPrimaryFooter;
this.GotoDocEnd();
this.AppendText(text,"黑体",9,"plain");
_oWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
}
public void InsertParaTitle(int level)
{
switch(level)
{
case 1:
_oDoc.Paragraphs.Last.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel1;
break;
case 2:
_oDoc.Paragraphs.Last.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel2;
break;
case 3:
_oDoc.Paragraphs.Last.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel3;
break;
case 4:
_oDoc.Paragraphs.Last.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel4;
break;
case 5:
_oDoc.Paragraphs.Last.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel5;
break;
case 6:
_oDoc.Paragraphs.Last.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel6;
break;
case 7:
_oDoc.Paragraphs.Last.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel7;
break;
case 8:
_oDoc.Paragraphs.Last.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel8;
break;
case 9:
_oDoc.Paragraphs.Last.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel9;
break;
default:
_oDoc.Paragraphs.Last.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevelBodyText;
break;
}
}
public void UpdateCatagory(float fontsize)
{
_oWord.ActiveDocument.TablesOfContents[1].RightAlignPageNumbers = true;
_oWord.ActiveDocument.TablesOfContents[1].Update();
_oWord.ActiveDocument.TablesOfContents[1].Range.Font.Size = fontsize;
_oWord.ActiveDocument.TablesOfContents[1].Range.Paragraphs.LineSpacingRule = Word.WdLineSpacing.wdLineSpace1pt5;
}
public void SetTableStyle()
{
for (int i = 1; i <= _oDoc.Tables.Count; i++)
{
_oDoc.Tables[i].Borders[Word.WdBorderType.wdBorderBottom].Color = Word.WdColor.wdColorBlack;
_oDoc.Tables[i].Borders[Word.WdBorderType.wdBorderTop].Color = Word.WdColor.wdColorBlack;
_oDoc.Tables[i].Borders[Word.WdBorderType.wdBorderLeft].Color = Word.WdColor.wdColorBlack;
_oDoc.Tables[i].Borders[Word.WdBorderType.wdBorderRight].Color = Word.WdColor.wdColorBlack;
_oDoc.Tables[i].Borders[Word.WdBorderType.wdBorderHorizontal].Color = Word.WdColor.wdColorBlack;
_oDoc.Tables[i].Borders[Word.WdBorderType.wdBorderVertical].Color = Word.WdColor.wdColorBlack;
_oDoc.Tables[i].Borders[Word.WdBorderType.wdBorderDiagonalDown].Color = Word.WdColor.wdColorBlack;
_oDoc.Tables[i].Borders[Word.WdBorderType.wdBorderDiagonalUp].Color = Word.WdColor.wdColorBlack;
}
}
///
/// 设定对齐
///
/// 对齐方式
public void SetAlignment(string AlignmentType)
{
switch (AlignmentType.ToLower())
{
case "center":
_oWord.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
break;
case "left":
_oWord.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
break;
case "right":
_oWord.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
break;
case "justify":
_oWord.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphThaiJustify;
break;
case "distribute":
_oWord.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphDistribute;
break;
}
}
///
/// 行距
///
///
public void SetLineSpacingRule(int spacePoint)
{
switch (spacePoint)
{
case 15:
_oDoc.Paragraphs.LineSpacingRule = Word.WdLineSpacing.wdLineSpace1pt5;
break;
case 1:
_oDoc.Paragraphs.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
break;
case 2:
_oDoc.Paragraphs.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceDouble;
break;
}
}
///
/// 段后距
///
///
public void SetSpaceAfter(float space)
{
_oDoc.Paragraphs.SpaceAfter = space; //段前、段后
}
///
/// 段前距
///
///
public void SetSpaceBefore(float space)
{
_oDoc.Paragraphs.SpaceBefore = space; //段前、段后
}
/**/
///
/// 首行缩进
///
/// float类型的数值
public void SetFirstLineIndent(float fltCount)
{
_oWord.Selection.ParagraphFormat.FirstLineIndent = fltCount;
}
/**/
///
/// 左缩进
///
/// float类型的数值
public void SetLeftIndent(float fltCount)
{
_oWord.Selection.ParagraphFormat.LeftIndent = fltCount;
}
/**/
///
/// 右缩进
///
/// float类型的数值
public void SetRightIndent(float fltCount)
{
_oWord.Selection.ParagraphFormat.RightIndent = fltCount;
}
///
/// 设置字体名称
///
/// 字体名称
public void SetFontName(string FontName)
{
_oWord.Selection.Font.Name = FontName;
}
///
/// 设置字体风格
///
/// 字体风格
public void SetFontStyle(string FontStyle)
{
switch (FontStyle.ToLower())
{
case "bold":
_oWord.Selection.Font.Bold = 1;
break;
case "plain":
_oWord.Selection.Font.Bold = 0;
break;
case "italic":
_oWord.Selection.Font.Italic = 1;
break;
case "underline":
_oWord.Selection.Font.Subscript = 1;
break;
case "strikethrough":
_oWord.Selection.Font.StrikeThrough = 1;
break;
}
}
///
/// 取消字体风格
///
public void DisabledFontStyle()
{
_oWord.Selection.Font.Bold = 0;
_oWord.Selection.Font.Italic = 0;
_oWord.Selection.Font.Underline = 0;
_oWord.Selection.Font.StrikeThrough = 0;
}
///
/// 设定字号
///
/// 字号
public void SetFontSize(int Size)
{
_oWord.Selection.Font.Size = Size;
}
///
/// 设置颜色
///
///
public void SetFontColor(Word.WdColor Color)
{
_oWord.Selection.Font.Color = Color;
}
#endregion
#region 选择
///
/// 选择页眉
///
public void SelectPageHeader()
{
if (_oWord.ActiveWindow.View.SplitSpecial != Word.WdSpecialPane.wdPaneNone)
_oWord.ActiveWindow.Panes[2].Close();
if (_oWord.ActiveWindow.View.Type == Word.WdViewType.wdNormalView || _oWord.ActiveWindow.View.Type == Word.WdViewType.wdOutlineView)
_oWord.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdPrintView;
_oWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader;
}
///
/// 选择页脚
///
public void SelectPageFooter()
{
if (_oWord.ActiveWindow.View.SplitSpecial != Word.WdSpecialPane.wdPaneNone)
_oWord.ActiveWindow.Panes[2].Close();
if (_oWord.ActiveWindow.View.Type == Word.WdViewType.wdNormalView || _oWord.ActiveWindow.View.Type == Word.WdViewType.wdOutlineView)
_oWord.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdPrintView;
_oWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
}
///
/// 设置页面切换到主页面
///
public void SetDocSeekViewToMainDocument()
{
_oWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
}
///
/// 选择段落文本
///
/// 段落
public void SelectRange(int Para)
{
_oDoc.Paragraphs[Para].Range.Select();
}
///
/// 选择文本
///
/// 段落
/// 句子
public void SelectRange(int para, int Sentences)
{
_oDoc.Paragraphs[para].Range.Sentences[Sentences].Select();
}
///
/// 选择文本
///
/// 开始处
/// 结束处
public void SelectRange(long start, long end)
{
object startPos = start;
object endPos = end;
_oDoc.Range(ref startPos, ref endPos).Select();
}
///
/// 查找书签
///
/// 书签名称
public void FindBookMark(string BookMark)
{
object goToBookMark = (int)Word.WdGoToItem.wdGoToBookmark;
object bookmark = BookMark;
_oWord.Selection.GoTo(ref goToBookMark, ref _oMissing, ref _oMissing, ref bookmark);
}
///
/// 修改书签
///
/// 书签名称
/// 新名称
public void ChangeBookMarkText(string BookMark,string newText)
{
object goToBookMark = (int)Word.WdGoToItem.wdGoToBookmark;
object bookmark = BookMark;
_oWord.Selection.GoTo(ref goToBookMark, ref _oMissing, ref _oMissing, ref bookmark).Text = newText;
}
///
/// 判断书签是否存在
///
/// 书签名称
///
public bool BookMarkExists(string BookMark)
{
return _oDoc.Bookmarks.Exists(BookMark);
}
///
/// 转到文档开头
///
public void GotoDocBegin()
{
object unit = Word.WdUnits.wdStory;
_oWord.Selection.HomeKey(ref unit, ref _oMissing);
}
///
/// 转到文档结尾
///
public void GotoDocEnd()
{
object unit = Word.WdUnits.wdStory;
_oWord.Selection.EndKey(ref unit, ref _oMissing);
}
///
/// 转到表格
///
///
public void GoToTheTable(int ntable)
{
object what = Word.WdUnits.wdTable;
object which = Word.WdGoToDirection.wdGoToFirst;
object count = ntable;
_oWord.Selection.GoTo(ref what, ref which, ref count, ref _oMissing);
_oWord.Selection.Find.ClearFormatting();
_oWord.Selection.Text = "";
}
///
/// 转到某个表格的某个单元格
///
/// 表格序号
/// 行号
/// 列号
public void GotoTableCell(int nTable, int nRow, int nColumn)
{
_oDoc.Tables[nTable].Cell(nRow, nColumn).Range.Select();
}
///
/// 获取某个表格的某个单元格
///
/// 表格序号
/// 行号
/// 列号
public string GetTableCellValue(int nTable, int nRow, int nColumn)
{
return _oDoc.Tables[nTable].Cell(nRow, nColumn).Range.Text;
}
///
/// 转到右边单元格
///
public void GoToRightCell()
{
// Selection.MoveRight Unit:=wdCell
object direction = Word.WdUnits.wdCell;
_oWord.Selection.MoveRight(ref direction, ref _oMissing, ref _oMissing);
}
///
/// 转到左边单元格
///
public void GoToLeftCell()
{
// Selection.MoveRight Unit:=wdCell
object direction = Word.WdUnits.wdCell;
_oWord.Selection.MoveLeft(ref direction, ref _oMissing, ref _oMissing);
}
///
/// 表格中转到下面的单元格
///
public void GoToDownCell()
{
// Selection.MoveRight Unit:=wdCell
object direction = Word.WdUnits.wdLine;
_oWord.Selection.MoveDown(ref direction, ref _oMissing, ref _oMissing);
}
///
/// 表格中转到上面的单元格
///
public void GoToUpCell()
{
// Selection.MoveRight Unit:=wdCell
object direction = Word.WdUnits.wdLine;
_oWord.Selection.MoveUp(ref direction, ref _oMissing, ref _oMissing);
}
#endregion
#region 插入文件
///
/// 插入图片到WORD文档中
///
/// 文件名称
public void InsertPicture(string FileName)
{
object LinkToFile = false;//链接到文件
object SaveWithDocument = true;//保存到文档中
_oWord.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref _oMissing);
//bm.Range.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref _oMissing);
}
///
/// 插入WORD文件
///
/// 文件名称
public void InsertWordFile(string FileName)
{
object ConfirmConversions = false;//是否提醒
object Link = false;//是否做为链接
object Attachment = false;//是否做为附件
_oWord.Selection.InsertFile(FileName, ref _oMissing, ref ConfirmConversions, ref Link, ref Attachment);
}
#endregion
#region 保存
public void SavaAs(object path) //保存文件
{
object format = Word.WdSaveFormat.wdFormatDocument;
_oDoc.SaveAs(ref path, ref format, 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);
}
#endregion
#region 删除文件
///
/// 删除文件
///
/// 文件名
public void FileDelete(string AbsoluteFilePath)
{
try
{
System.IO.FileInfo objFile = new System.IO.FileInfo(AbsoluteFilePath);
if (objFile.Exists)//如果存在
{
//删除文件.
objFile.Delete();
}
objFile = null;
}
catch
{
}
}
#endregion
#region 关闭所有WINWORD进程
///
/// 关闭文档
///
public void CloseWordAndDoc()//善后处理
{
if (_oWord != null && _oDoc!=null)
{
_oWord.Quit(ref _oMissing, ref _oMissing, ref _oMissing);
_oDoc = null;
_oWord = null;
}
}
///
/// 杀除所有WINWORD进程
///
public void KillWinWord()
{
this.Dispose();
GC.Collect();
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if (p.ProcessName.ToLower() == "winword")
p.Kill();
}
}
#endregion
}
}
------------------------------------------------------结束-----------------------------------------------------------------
操作实例:
IDocManager Docmanager = new DocManager();
Docmanager.Add(@"D:/test.doc");//打开文件并复制模板到其中
写标签数据:
foreach (Word.Bookmark bm in Docmanager.Document.Bookmarks)
{
if (bm.Name == "B1")
{
Docmanager.setRangleText(bm, "成功添加到第一个标签");
}
else if (bm.Name == "B2")
{
Docmanager.setRangleText(bm, "成功添加到第二个标签");
}
插入图片:
public void InsertPic()
{
string picfilename = @"D:/test.jpg";
try
{
if (File.Exists(picfilename))
{
Docmanager.FindBookMark("InsertPIC");
Docmanager.AppendText(" ");
Docmanager.InsertParaTitle(0);
Docmanager.InsertPicture(picfilename);
File.Delete(picfilename);
}
}
catch (Exception ex) {
throw;
}
}
页眉页脚:
public void InsertDocFooter()
{
Docmanager.SetPageFooter("页脚");
}//页脚
public void InsertDocHeader()
{
Docmanager.SetPageHeader("页眉");
}//页眉
段落设置:
public void SetParagraphs() // {
Docmanager.SetSpaceAfter(0); //段前
Docmanager.SetSpaceBefore(0); //段后
Docmanager.SetLineSpacingRule(15);//行距1.5倍
Docmanager.SetFirstLineIndent(2);//首行缩进m³
}
更新目录:
public void UpdateCatagory()
{
float fontsize = 10;
Docmanager.UpdateCatagory(fontsize);
}
转到文档结尾:
Docmanager.GotoDocEnd();