1、 word文档操作
下面功能实现都是用com组件完成。添加引用 MSWord = Microsoft.Office.Interop.Word;
Winfrom操作界面
(1)获取word文档的总页数
private Word.Document _wordDocument; int pageNumber = 0; Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages; pageNumber = _wordDocument.ComputeStatistics(stat, ref missing);
(2)定义页面跳转方法
/// <summary> /// 跳转到指定页 /// </summary> /// <param name="_wordDocument"></param> /// <param name="n"></param> public void GoToPage(Word.Document _wordDocument,string n) { object What = Word.WdGoToItem.wdGoToPage; object Which = Word.WdGoToDirection.wdGoToNext; object Name = n; _wordDocument.ActiveWindow.Selection.GoTo(ref What, ref Which, ref missing, ref Name); _wordDocument.ActiveWindow.Selection.Paragraphs[1].Range.Text.ToString(); }
(3)上页、下页、首页、尾页跳转
定义全局变量currentPage,记录当前显示的页面
/// <summary> /// 上一页 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Preview_Click(object sender, EventArgs e) { if (currentPage-- > 1) { wordDocemrent.GoToPage(wordDocemrent.WordDocument, currentPage.ToString()); } } /// <summary> /// 下一页 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Nextview_Click(object sender, EventArgs e) { if (currentPage++ < pageNumber) { wordDocemrent.GoToPage(wordDocemrent.WordDocument, currentPage.ToString()); } } /// <summary> /// 第一页 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FristPage_Click(object sender, EventArgs e) { wordDocemrent.GoToPage(wordDocemrent.WordDocument, "1"); currentPage = 1; } /// <summary> /// 末页 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void EndPage_Click(object sender, EventArgs e) { wordDocemrent.GoToPage(wordDocemrent.WordDocument, pageNumber.ToString()); currentPage = pageNumber; }
(4)word滚动
从textbox空间传入值,可操作word文档光标位置,模拟鼠标滚动条
/// <summary> /// 光标上移 /// </summary> public int MoveUp(object unit, object count, object extend) { return _wordApplication.Selection.MoveUp(ref unit, ref count, ref extend); } /// <summary> /// 光标下移 /// </summary> public int MoveDown(object unit, object count, object extend) { return _wordApplication.Selection.MoveDown(ref unit, ref count, ref extend); }
(5)word 转换成图片
private Bitmap[] WordtoImage(string filePath) { string tmpPath = AppDomain.CurrentDomain.BaseDirectory + "\\" + Path.GetFileName(filePath) + ".tmp"; File.Copy(filePath, tmpFilePath); List<Bitmap> imageLst= new List<Bitmap>();
MSWord.Application wordApplicationClass = new MSWord.Application(); wordApplicationClass.Visible = false; object missing = System