• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
繁星
不要浪费时间
博客园    首页    新随笔    联系   管理    订阅  订阅

实现动态添加数据打印word预览

  /// <summary>
        /// 实现动态添加数据打印预览
        /// </summary>
        /// <param name="path">word模板路径</param>
        /// <param name="pathprint">word打印路径</param>
        public void PrintPreview(string path, string pathprint)
        {
            WordApplication word = null;
            Document doc = null;
            Document printDoc = null;
            object oMissing = System.Reflection.Missing.Value;
            object oMissing2 = System.Reflection.Missing.Value;


            if (word == null)
            {
                word = new WordApplication();
            }
            object path1 = (object)path;
            object path2 = (object)pathprint;

            doc = word.Documents.OpenOld(ref path1, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            printDoc = word.Documents.OpenOld(ref path2, ref oMissing2, ref oMissing2, ref oMissing2, ref oMissing2, ref oMissing2, ref oMissing2, ref oMissing2, ref oMissing2, ref oMissing2);
            printDoc.Content.Text = null;//清空word打印
            doc.Content.Copy(); //复制doc里的内容,doc是每次做替换书签的文档.
            object save = false;
            doc.Close(ref save, ref oMissing, ref oMissing); //关闭doc.
            Range range = printDoc.Content; //全中printDoc里的全部内容,printDoc是目标保存文档.
            range.Collapse(ref oMissing);
            range.Paste();
            try
            {
                #region 替换书签

                foreach (Bookmark BM in printDoc.Bookmarks)
                {
                    switch (BM.Name)
                    {

                        case "姓名":
                            BM.Select();
                            BM.Range.Text = "xxxxxx";
                            break;
                        case "性别":
                            BM.Select();
                            BM.Range.Text = "男";
                            break;
                    }
                }


                #endregion
                word.Visible = true;
                printDoc.PrintPreview();
            }

            catch (Exception ex)
            {
                object save2 = false;
                printDoc.Close(ref save2, ref oMissing2, ref oMissing2); //关闭doc.
                MessageBox.Show(ex.Message.ToString());
            }
        }

posted @ 2009-03-11 22:17  ※繁星※  阅读(2232)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3