private void btnInDanhSach_Click(object sender, EventArgs e)
        {
            if (grvSinhVien.DataRowCount > 0)
            {
                CreateWaitDialog("Đang xuất dữ liệu, xin vui lòng chờ.", "Xuất dữ liệu");
                try
                {
                    Lib.clsExportToWord cls = new Lib.clsExportToWord();
                    Microsoft.Office.Interop.Word.ApplicationClass WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                    Microsoft.Office.Interop.Word.Document         aDoc    = null;
                    cls.InitWord(WordApp, ref aDoc, 12);

                    cls.AddText(aDoc, "Danh sách sinh viên " + pDM_LopInfo.TenLop + (cboDanhSachHienThi.SelectedIndex == 1 ? " (đã bị xóa tên)" : ""), 1, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter, 16);

                    cls.AddText(aDoc, "", 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft, 12);
                    cls.AddTable(aDoc, dtSinhVien, new string[] { "Mã sinh viên", "Họ và tên", "Ngày sinh", "Nơi sinh", "Thường trú", "Khen thưởng", "Kỷ luật" },
                                 new string[] { "MaSinhVien", "HoVaTen", "NgaySinh", "NoiSinh", "ThuongTru", "KhenThuong", "KyLuat" });

                    WordApp.Visible = true;
                    CloseWaitDialog();
                }
                catch (Exception ex)
                {
                    CloseWaitDialog();
                    ThongBaoLoi("Có lỗi khi xuất dữ liệu. " + ex.Message);
                }
            }
            else
            {
                ThongBao("Chưa có danh sách sinh viên.");
            }
        }
示例#2
0
        /// <summary>
        /// needed designer variable
        /// </summary>
        //  private System.ComponentModel.Container components = null;

        /// <summary>
        /// Preactivation
        /// It's usefull, if you need more speed in the main Program
        /// so you can preload Word.
        /// </summary>
        public void PreActivate()
        {
            if (wd == null)
            {
                wd = new Microsoft.Office.Interop.Word.ApplicationClass();
            }
        }
示例#3
0
        /// <summary>
        /// 读取word内容
        /// </summary>
        /// <param name="docpath">word文档路径</param>
        /// <returns></returns>
        public void DealWord(string docpath)
        {
            string moreThanCharacter = "Evaluation Only. Created with Aspose.Words. Copyright 2003-2014 Aspose Pty Ltd.";

            //实例化COM
            Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            object fileobj = docpath;
            object nullobj = System.Reflection.Missing.Value;

            //打开指定文件(不同版本的COM参数个数有差异,一般而言除第一个外都用nullobj就行了)
            Microsoft.Office.Interop.Word.Document doc = wordApp.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);
            foreach (Microsoft.Office.Interop.Word.Shape shape in doc.Shapes)
            {
                if (shape.Name.Equals(moreThanCharacter))
                {
                    shape.Delete();
                    break;
                }
            }

            //取得doc文件中的文本
            // string outText = doc.Content.Text;
            //关闭文件
            doc.Close(ref nullobj, ref nullobj, ref nullobj);
            //关闭COM
            wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);
            //返回
            // return outText;
        }
示例#4
0
        /// <summary>
        /// Imports from word.
        /// </summary>
        /// <param name="filename">The filename.</param>
        public static bool ImportFromWord(RichTextBox Rich, String filename)
        {
            try
            {
                Microsoft.Office.Interop.Word.ApplicationClass wordApp =
                                new Microsoft.Office.Interop.Word.ApplicationClass();

                object fileName = filename;
                object objFalse = false;
                object objTrue = true;
                object missing = System.Reflection.Missing.Value;

                Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(
                ref fileName, ref objFalse, ref objTrue, ref objFalse, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref objTrue, ref missing, ref missing, ref missing, ref missing);

                doc.ActiveWindow.Selection.WholeStory();
                doc.ActiveWindow.Selection.Copy();

                IDataObject data = Clipboard.GetDataObject();
                Rich.Rtf = data.GetData(DataFormats.Rtf).ToString();
                wordApp.Quit(ref missing, ref missing, ref missing);

                return true;
            }
            catch
            {
                PLMessageBoxDev.ShowMessage("Microsoft Word chưa cài đặt trên máy.");
                return false;
            }
        }
示例#5
0
        /// <summary>
        /// word转html
        /// </summary>
        /// <param name="wordFileName">word文档访问路径(服务器绝对路径)</param>
        /// <param name="htmlWord">html保存目录(服务器绝对路径)</param>
        /// <returns>true/false</returns>
        private bool WordToHtml(string wordFileName, string htmlWord)
        {
            bool isConvert = false;

            Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
            Type wordType = word.GetType();

            Microsoft.Office.Interop.Word.Documents docs = word.Documents;
            try
            {
                //打开文件
                Type docsType = docs.GetType();
                Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { wordFileName, true, true });
                Type docType = doc.GetType();
                //转换格式,另存为
                string wordSaveFileName = wordFileName.ToString();
                string strSaveFileName  = htmlWord + "\\" + Path.GetFileNameWithoutExtension(wordSaveFileName) + ".html";
                object saveFileName     = (object)strSaveFileName;
                docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML });
                //关闭文件
                docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
                isConvert = true;
            }
            catch (Exception ex)
            {
                isConvert = false;
            }
            //退出Word
            wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
            return(isConvert);
        }
示例#6
0
        /// <summary>
        /// Word转成Html
        /// </summary>
        /// <param name="filePath">word文档路径</param>
        /// <param name="htmlPath">保存的html路径</param>
        /// <returns>是否成功</returns>
        public static bool WordToHtml(string filePath, string htmlPath = null)
        {
            var  flg      = false;
            var  word     = new Microsoft.Office.Interop.Word.ApplicationClass();
            Type wordType = word.GetType();

            Microsoft.Office.Interop.Word.Documents docs = word.Documents;
            Type docsType = docs.GetType();

            Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { (object)filePath, true, true });
            Type docType = doc.GetType();

            string strSaveFileName = htmlPath ?? System.IO.Path.ChangeExtension(filePath, "html");

            object saveFileName = (object)strSaveFileName;

            try
            {
                docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML });
                flg = true;
            }
            catch (Exception ex) { throw ex; }
            try
            {
                docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
                wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
            }
            catch { }
            return(flg);
        }
        private void btnPhanBoChiTiet_Click(object sender, EventArgs e)
        {
            if (IDKQHT_ChuongTrinhDaoTao > 0)
            {
                Lib.clsExportToWord cls = new Lib.clsExportToWord();

                DataTable dt = oBXL_MonHocTrongKy.GetMonKyToanKhoaByLop(IDDM_Lop);
                if (dt.Rows.Count > 0)
                {
                    Microsoft.Office.Interop.Word.ApplicationClass WordApp;
                    CreateWaitDialog("Xuất dữ liệu", "Đang xuất dữ liệu ra file");
                    try
                    {
                        WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                        Microsoft.Office.Interop.Word.Document aDoc = null;
                        cls.InitWord(WordApp, ref aDoc, 13);

                        DataTable dtNamKy = new Lib.clsDataTableHelper().SelectDistinct(dt, new string[] { "TenNamHoc", "HocKy" });
                        Dictionary <int, float> colWidth = new Dictionary <int, float>();
                        colWidth.Add(1, 7);
                        for (int i = 2; i <= 5; i++)
                        {
                            colWidth.Add(i, 2);
                        }

                        foreach (DataRow dr in dtNamKy.Rows)
                        {
                            DataView dv = new DataView(dt);
                            dv.RowFilter = "TenNamHoc = '" + dr["TenNamHoc"] + "' And HocKy = " + dr["HocKy"];
                            cls.AddText(aDoc, "\tCác môn học trong học kỳ " + dr["HocKy"] + " năm học " + dr["TenNamHoc"], 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft);
                            //cls.AddTable(aDoc, dv.ToTable(), new string[] { "Tên môn học", "Số học trình", "Số tiết", "Lý thuyết", "Thực hành" },
                            //    new string[] { "TenMonHoc", "SoHocTrinh", "SoTiet", "LyThuyet", "ThucHanh" });

                            cls.AddTable(WordApp, aDoc, dv.ToTable(), new string[] { "Tên môn học", "Số học trình", "Số tiết", "Lý thuyết", "Thực hành" },
                                         new string[] { "TenMonHoc", "SoHocTrinh", "SoTiet", "LyThuyet", "ThucHanh" }, colWidth);

                            cls.AddText(aDoc, "", 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft);
                        }
                        WordApp.Visible = true;
                        CloseWaitDialog();
                    }
                    catch (Exception ex)
                    {
                        CloseWaitDialog();
                        ThongBaoLoi("File word đang được mở. Đề nghị đóng file này trước khi xuất dữ liệu! Thông báo lỗi: " + ex.Message);
                        return;
                    }
                }
                else
                {
                    ThongBao("Lớp này chưa được phân bổ các môn trong kỳ.");
                }
            }
            else
            {
                ThongBao("Lớp này chưa có chương trình đào tạo");
            }
        }
示例#8
0
        void Button12Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();                    //inisial variabel pembuka file

            dialog.Filter           = "Document PDF|*.pdf|File Word|*.docx"; //inisial ekstensi file yang akan dibuka
            dialog.Title            = "Open File : ";
            dialog.RestoreDirectory = true;

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                tipe2 = dialog.FileName.Substring(dialog.FileName.Length - 4, 4);
                tipe  = dialog.FileName.Substring(dialog.FileName.Length - 3, 3);
                if (tipe == "pdf")
                {
                    baca           = new PdfReader(dialog.FileName);
                    textBox14.Text = dialog.FileName;
                    tipe           = dialog.FileName.Substring(dialog.FileName.Length - 3, 3);
                    int      intPageNum = baca.NumberOfPages;
                    string[] words;
                    string   line, text;
                    string   temp = "";
                    for (int i = 1; i <= intPageNum; i++)
                    {
                        text  = PdfTextExtractor.GetTextFromPage(baca, i, new LocationTextExtractionStrategy());
                        words = text.Split('\n');
                        for (int j = 0, len = words.Length; j < len; j++)
                        {
                            line  = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(words[j]));
                            temp += line + Environment.NewLine;
                        }
                    }
                    richTextBox6.Text = temp;
                }
                else if (tipe2 == "docx")
                {
                    Microsoft.Office.Interop.Word.Application wordApp = new
                                                                        Microsoft.Office.Interop.Word.ApplicationClass();
                    object filenameO = dialog.FileName;
                    object objFalse  = false;
                    object objTrue   = true;
                    object missing   = System.Reflection.Missing.Value;
                    object emptyData = string.Empty;


                    Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(ref filenameO, ref objFalse, ref objTrue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref objTrue, ref missing, ref missing, ref missing, ref missing);

                    aDoc.ActiveWindow.Selection.WholeStory();
                    aDoc.ActiveWindow.Selection.Copy();

                    IDataObject data     = System.Windows.Forms.Clipboard.GetDataObject();
                    String      fileText = data.GetData(System.Windows.Forms.DataFormats.Text).ToString();
                    System.Windows.Forms.Clipboard.SetDataObject(string.Empty);

                    richTextBox6.Text = fileText;
                }
            }
        }
示例#9
0
        public static void PrintWord(object FileName, string ConnectionString, string coTitle, string sFontName, string Lang, string where,
                                     string where1, string where2, string where3, string where4, string where5, string where6, string where7, string where8,
                                     string where9, string where10, string User)
        {
            object oMissing = Missing.Value;

            Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Documents   oDocs = oWord.Documents;
            Microsoft.Office.Interop.Word._Document   oDoc  = null;

            System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            try
            {
                oDoc = oDocs.Open(ref FileName, 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);
                oWord.Visible = true;

                //Cap nhat properties
                SetProperty(oDoc, "ConnectionString", ConnectionString);
                SetProperty(oDoc, "CoTitle", coTitle);
                SetProperty(oDoc, "sFontName", sFontName);
                SetProperty(oDoc, "Lang", Lang);
                SetProperty(oDoc, "where", where);
                SetProperty(oDoc, "where1", where1);
                SetProperty(oDoc, "where2", where2);
                SetProperty(oDoc, "where3", where3);
                SetProperty(oDoc, "where4", where4);
                SetProperty(oDoc, "where5", where5);
                SetProperty(oDoc, "where6", where6);
                SetProperty(oDoc, "where7", where7);
                SetProperty(oDoc, "where8", where8);
                SetProperty(oDoc, "where9", where9);
                SetProperty(oDoc, "where10", where10);
                SetProperty(oDoc, "User", User);

                try
                {
                    RunMacro(oWord, new object[] { "CreatReport" });
                }
                catch {}
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "Error!");
            }
            finally
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oDocs);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
                GC.Collect();
            }
        }
        /// <summary>
        /// Word 转换成 HTML 文件
        /// </summary>
        /// <param name="wordPath">Word 文档路径</param>
        /// <param name="htmlPath">Html 文件路径</param>
        public static void WordToHtmlFile(string wordPath, string htmlPath)
        {
            if (string.IsNullOrEmpty(wordPath))
            {
                throw new Exception(WordPathNullException);
            }

            Microsoft.Office.Interop.Word.ApplicationClass applicationClass = new Microsoft.Office.Interop.Word.ApplicationClass();
            Type wordType = applicationClass.GetType();

            Microsoft.Office.Interop.Word.Documents documents = applicationClass.Documents;

            // 打开文件
            Type documentsType = documents.GetType();

            Microsoft.Office.Interop.Word.Document document = (Microsoft.Office.Interop.Word.Document)documentsType.InvokeMember("Open",
                                                                                                                                 System.Reflection.BindingFlags.InvokeMethod, null, documents, new Object[] { wordPath, true, true });

            // 转换格式,另存为html
            Type documentType = document.GetType();

            string directoryPath     = Path.GetDirectoryName(htmlPath);
            string fileDirectoryPath = Path.Combine(directoryPath, Path.GetFileNameWithoutExtension(htmlPath));

            /*下面是Microsoft Word 9 Object Library的写法,如果是10,可能写成:
             * docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
             * null, doc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML});
             * 其它格式:
             * wdFormatHTML
             * wdFormatDocument
             * wdFormatDOSText
             * wdFormatDOSTextLineBreaks
             * wdFormatEncodedText
             * wdFormatRTF
             * wdFormatTemplate
             * wdFormatText
             * wdFormatTextLineBreaks
             * wdFormatUnicodeText
             */
            documentType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
                                      null, document, new object[] { htmlPath, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML });

            //关闭文档
            documentType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod,
                                      null, document, new object[] { null, null, null });

            // 退出 Word
            wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, applicationClass, null);

            //转化HTML页面统一编码格式
            TransformHTMLEncoding(htmlPath);
        }
示例#11
0
        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="printName"></param>
        /// <returns></returns>
        public bool printByOffice(string printName)
        {
            if (printFilePathList.Count == 1)
            {
                //foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("WINWORD"))
                //{
                //    p.Kill();
                //}
            }
            //打印
            Microsoft.Office.Interop.Word.Application app = null;
            Microsoft.Office.Interop.Word.Document    doc = null;
            object missing      = System.Reflection.Missing.Value;
            object templateFile = System.IO.Path.GetFullPath(printFilePath);

            //System.IO.Path.GetFullPath("TextFile1.txt")
            try
            {
                app = new Microsoft.Office.Interop.Word.ApplicationClass();
                doc = app.Documents.Add(ref templateFile, ref missing, ref missing, ref missing);

                //保存默认打印机
                defaultPrintName  = DefaultPrinter();
                app.ActivePrinter = printName;

                //打印
                doc.PrintOut(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            }
            catch (Exception exp)
            {
                //object saveChange = Microsoft.Office.Interop.Word.WdSaveOptions.wdPromptToSaveChanges;// .wdDoNotSaveChanges;
                //if (doc != null)
                //    doc.Close(ref saveChange, ref missing, ref missing);
                //if (app != null)
                //    app.Quit(ref missing, ref missing, ref missing);

                //foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("WINWORD"))
                //{
                //    p.Kill();
                //}
                throw exp;
            }
            finally
            {
                //删除文件
                //existsFile(templateFile.ToString());
            }
            return(true);
        }
        private void btnInQuyetDinh_Click(object sender, EventArgs e)
        {
            if (dtNangBacChuyenNgach.Rows.Count > 0)
            {
                CreateWaitDialog("Đang xuất dữ liệu, xin vui lòng chờ.", "Xuất dữ liệu");
                try
                {
                    // Khoi tao ban word.
                    Microsoft.Office.Interop.Word.ApplicationClass WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                    Microsoft.Office.Interop.Word.Document         aDoc    = null;
                    clsWord.InitWord(WordApp, ref aDoc, 11);
                    // Insert du lieu vao ban word.
                    // Tieu de trang
                    if (Them == true)
                    {
                        clsWord.AddText(aDoc, "QUYẾT ĐỊNH SỐ " + txtSoQuyetDinh.Text, 1, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter);
                    }
                    if (Sua == true)
                    {
                        clsWord.AddText(aDoc, "QUYẾT ĐỊNH SỐ " + dtNangBacChuyenNgach.Rows[0]["SoQuyetDinh"], 1, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter);
                    }
                    clsWord.AddText(aDoc, "Về việc nâng bậc lương - chuyển ngạch", 1, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter);
                    clsWord.AddText(aDoc, "đối với cán bộ công nhân viên chức", 1, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter);

                    // Noi dung trang

                    // Insert qua trinh cong tac vao bang
                    clsWord.AddText(aDoc, "Điều 1. Nâng bậc lương, chuyển ngạch cho " + dtNangBacChuyenNgach.Rows.Count + " cán bộ, công nhân viên chức " + Program.TenTruong + "."
                                    , 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft);
                    for (int i = 0; i < dtNangBacChuyenNgach.Rows.Count; i++)
                    {
                        dtNangBacChuyenNgach.Rows[i]["STT"] = i + 1;
                    }
                    clsWord.AddTable(aDoc, dtNangBacChuyenNgach, new string[] { "STT", "Họ và tên", "Mã ngạch", "Bậc lương", "Hệ số", "Mức hưởng(%)", "Từ ngày", "Đế ngày" },
                                     new string[] { "STT", "HoTen", "MaNgachCongChuc", "BacLuong", "HeSoLuong", "PhanTramHuong", "TuNgay", "LuongDenNgay" });
                    clsWord.AddText(aDoc, "", 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft);
                    clsWord.AddText(aDoc, "Điều 2. Các ông (bà) Chánh Văn phòng, Vụ trưởng Vụ Tổ chức cán bộ, Vụ trưởng Vụ Kế hoạch - Tài chính, Hiệu trưởng " + Program.TenTruong + " và các ông, bà có tên trong danh sách tại Điều 1 chịu trách nhiệm thi hành Quyết định này./."
                                    , 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft);
                    WordApp.Visible = true;
                    CloseWaitDialog();
                }
                catch (Exception ex)
                {
                    CloseWaitDialog();
                    ThongBaoLoi("Đang xuất dữ liệu, lỗi khi tắt chức năng này. " + ex.Message);
                }
            }
        }
示例#13
0
        private void bttDY_Click(object sender, EventArgs e)
        {
            try
            {
                if (!System.IO.File.Exists(wordPath.ToString()))
                {
                    return;
                }
                List <string> newValue = GettxtValue();
                //word应用
                Microsoft.Office.Interop.Word.ApplicationClass App = new Microsoft.Office.Interop.Word.ApplicationClass(); //Word应用程序对象
                Microsoft.Office.Interop.Word.Document         doc = new Microsoft.Office.Interop.Word.Document();         //Word文档对象
                App.Visible = false;
                String[] bmsTest = { "biaohao",    "zhibiaoriqi", "shujuneirong", "tigongdanwei", "suoqudanwei", "chulibumen", "xieyibianhao", "teshushuiming", "shujufanwei", "zhuyaoyongtu", "guodixin",   "miji",  "txtsn",     "txtpn",          "geshi", "shijitufushu", "jishufuwufeiyong", "shujuliang", "bumenfuzeren", "bumenqianzi", "jishujiagong", "txtjishujiang", "chenggujianchare",
                                     "qianziriqi", "jieshouren",  "aaaaa",        "querenqian",   "bbbbb",       "ddddd",      "ccccc",        "lianxiren",     "dianhua",     "youzheng",     "emaildizhi", "fffff", "beizhutxt", "zhibiaorenyuan", };
                object   oMissing     = System.Reflection.Missing.Value;
                object   readOnly     = false;
                object   saveFileName = Application.StartupPath + "\\..\\OrderTask\\teste.doc";

                doc = App.Documents.Open(ref wordPath, ref oMissing, ref readOnly,
                                         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);

                doc.Activate();
                int m = 0;
                //替换
                foreach (String s in bmsTest)
                {
                    Replace(doc, s, newValue[m]);
                    m++;
                }

                doc.SaveAs(ref saveFileName, 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, ref oMissing);
                doc.Close(ref oMissing, ref oMissing, ref oMissing);
                App.Quit(ref oMissing, ref oMissing, ref oMissing);

                //打开
                if (System.IO.File.Exists(saveFileName.ToString()))
                {
                    System.Diagnostics.Process.Start(saveFileName.ToString());
                }
                this.WindowState = FormWindowState.Minimized;
            }
            catch
            {
            }
        }
示例#14
0
        /// <summary>
        /// 获取Word文件页数【格式为doc,docx】
        /// </summary>
        public int GetWordPageCount(object filePath)
        {
            Microsoft.Office.Interop.Word.Application myWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            object oMissing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Document myWordDoc = myWordApp.Documents.Open(
                ref filePath, 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, ref oMissing);
            int pages = myWordDoc.ComputeStatistics(Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages, ref oMissing);

            myWordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
            myWordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
            return(pages);
        }
示例#15
0
        //fungsi untukmengambil tipe dokumen
        private void loadText()
        {
            if (tipe2 == "docx")
            {
                Microsoft.Office.Interop.Word.Application wordApp = new
                                                                    Microsoft.Office.Interop.Word.ApplicationClass();
                object filenameO = dialogg.FileName;
                object objFalse  = false;
                object objTrue   = true;
                object missing   = System.Reflection.Missing.Value;
                object emptyData = string.Empty;


                Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(ref filenameO, ref objFalse, ref objTrue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref objTrue, ref missing, ref missing, ref missing, ref missing);

                aDoc.ActiveWindow.Selection.WholeStory();
                aDoc.ActiveWindow.Selection.Copy();

                IDataObject data     = System.Windows.Forms.Clipboard.GetDataObject();
                String      fileText = data.GetData(System.Windows.Forms.DataFormats.Text).ToString();
                System.Windows.Forms.Clipboard.SetDataObject(string.Empty);

                richTextBox1.Text = fileText;
            }
            if (tipe == "doc")
            {
                Microsoft.Office.Interop.Word.Application wordApp = new
                                                                    Microsoft.Office.Interop.Word.ApplicationClass();
                object filenameO = dialogg.FileName;
                object objFalse  = false;
                object objTrue   = true;
                object missing   = System.Reflection.Missing.Value;
                object emptyData = string.Empty;


                Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(ref filenameO, ref objFalse, ref objTrue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref objTrue, ref missing, ref missing, ref missing, ref missing);

                aDoc.ActiveWindow.Selection.WholeStory();
                aDoc.ActiveWindow.Selection.Copy();

                IDataObject data     = System.Windows.Forms.Clipboard.GetDataObject();
                String      fileText = data.GetData(System.Windows.Forms.DataFormats.Text).ToString();
                System.Windows.Forms.Clipboard.SetDataObject(string.Empty);

                richTextBox1.Text = fileText;
            }
        }
示例#16
0
        /// <summary>
        /// Word转成Html
        /// </summary>
        /// <param name="path">要转换的文档的路径</param>
        /// <param name="savePath">转换成html的保存路径</param>
        /// <param name="wordFileName">转换成html的文件名字</param>
        public static void Word2Html(string path, string savePath, string wordFileName)
        {
            Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
            Type wordType = word.GetType();

            Microsoft.Office.Interop.Word.Documents docs = word.Documents;
            Type docsType = docs.GetType();

            Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { (object)path, true, true });
            Type   docType         = doc.GetType();
            string strSaveFileName = savePath + wordFileName + ".html";
            object saveFileName    = (object)strSaveFileName;

            docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML });
            docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
            wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
        }
示例#17
0
    public string wordToHtml(System.Web.UI.HtmlControls.HtmlInputFile wordFilePath)
    {
        Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
        Type wordType = word.GetType();

        Microsoft.Office.Interop.Word.Documents docs = word.Documents;
        // 打开文件
        Type docsType = docs.GetType();
        //应当先把文件上传至服务器然后再解析文件为html
        string filePath = uploadWord(wordFilePath);

        //判断是否上传文件成功
        if (filePath == "0")
        {
            return("0");
        }
        //判断是否为word文件
        if (filePath == "1")
        {
            return("1");
        }
        object fileName = filePath;

        Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open",
                                                                                                                   System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { fileName, true, true });
        // 转换格式,另存为html
        Type   docType  = doc.GetType();
        string filename = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() +
                          System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString();
        //被转换的html文档保存的位置
        string ConfigPath   = HttpContext.Current.Server.MapPath("~/keyfile/a.html");
        object saveFileName = ConfigPath;


        docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
                             null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML });
        //关闭文档
        docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod,
                             null, doc, new object[] { null, null, null });
        // 退出 Word
        wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
        //转到新生成的页面
        return("/" + filename + ".html");
    }
        private void btnInDanhSach_Click(object sender, EventArgs e)
        {
            if (grvSinhVien.DataRowCount > 0)
            {
                Lib.clsExportToWord cls = new Lib.clsExportToWord();
                Microsoft.Office.Interop.Word.ApplicationClass WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                Microsoft.Office.Interop.Word.Document         aDoc    = null;
                cls.InitWord(WordApp, ref aDoc, 12);
                cls.AddText(aDoc, "Danh sách sinh viên được cấp quyền", 1, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter, 16);
                if (cmbHe.ItemIndex > -1)
                {
                    cls.AddText(aDoc, "\tHệ: " + cmbHe.Text, 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft, 12);
                }
                if (cmbTrinhDo.ItemIndex > -1)
                {
                    cls.AddText(aDoc, "\tTrình độ: " + cmbTrinhDo.Text, 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft, 12);
                }
                if (cmbKhoa.ItemIndex > -1)
                {
                    cls.AddText(aDoc, "\tKhoa: " + cmbKhoa.Text, 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft, 12);
                }
                if (cmbNganh.ItemIndex > -1)
                {
                    cls.AddText(aDoc, "\tNgành: " + cmbNganh.Text, 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft, 12);
                }
                if (cmbKhoaHoc.ItemIndex > -1)
                {
                    cls.AddText(aDoc, "\tKhóa: " + cmbKhoaHoc.Text, 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft, 12);
                }
                if (cmbLop.ItemIndex > -1)
                {
                    cls.AddText(aDoc, "\tLớp: " + cmbLop.Text, 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft, 12);
                }

                cls.AddText(aDoc, "", 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft, 12);
                cls.AddTable(aDoc, dtSinhVien, new string[] { "Mã sinh viên", "Họ và tên", "Ngày sinh", "Lớp", "Tên đăng nhập" },
                             new string[] { "MaSinhVien", "HoVaTen", "NgaySinh", "TenLop", "TenDangNhap" });
            }
            else
            {
                ThongBao("Không có danh sách sinh viên.");
            }
        }
        /// <summary>
        /// 把Word文件转换成为PDF格式文件
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public static bool WordToPDF(string sourcePath, string targetPath)
        {
            bool result = false;

            Microsoft.Office.Interop.Word.WdExportFormat   exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
            Microsoft.Office.Interop.Word.ApplicationClass application  = null;

            Microsoft.Office.Interop.Word.Document document = null;
            try
            {
                application = new Microsoft.Office.Interop.Word.ApplicationClass {
                    Visible = false
                };
                document = application.Documents.Open(sourcePath);
                document.SaveAs();
                document.ExportAsFixedFormat(targetPath, exportFormat);
                result = true;
            }
            catch (Exception e)
            {
                result = false;
                throw new Exception(e.Message);
            }
            finally
            {
                if (document != null)
                {
                    document.Close();
                    document = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return(result);
        }
示例#20
0
        private void btnInDanhSach_Click(object sender, EventArgs e)
        {
            if (grvGiaoVien.DataRowCount > 0)
            {
                try
                {
                    var cloneData = dtGiaoVien.Copy();
                    CreateWaitDialog("Đang xuất dữ liệu, xin vui lòng chờ.", "Xuất dữ liệu");

                    foreach (DataRow dr in cloneData.Rows)
                    {
                        if ("" + dr["Password"] != "")
                        {
                            dr["Password"] = Lib.clsAuthentication.Decrypt("" + dr["Password"]);
                        }
                    }

                    Lib.clsExportToWord cls = new Lib.clsExportToWord();
                    Microsoft.Office.Interop.Word.ApplicationClass WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                    Microsoft.Office.Interop.Word.Document         aDoc    = null;

                    cls.InitWord(WordApp, ref aDoc, 12);
                    cls.AddText(aDoc, "Danh sách giảng viên được cấp quyền", 1, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter, 16);

                    cls.AddText(aDoc, "\tĐơn vi: " + pDonViInfo.TenDonVi, 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft, 12);

                    cls.AddText(aDoc, "", 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft, 12);
                    cls.AddTable(aDoc, cloneData, new string[] { "Mã giáo viên", "Họ và tên", "Ngày sinh", "Tên đăng nhập", "Mật khẩu" },
                                 new string[] { "MaGiaoVien", "HoTen", "NgaySinh", "Username", "Password" });
                    WordApp.Visible = true;
                    CloseWaitDialog();
                }
                catch
                {
                    CloseWaitDialog();
                }
            }
            else
            {
                ThongBao("Không có danh sách giảng viên.");
            }
        }
示例#21
0
        /// <summary>
        /// 打印预览
        /// </summary>
        /// <param name="printName"></param>
        /// <returns></returns>
        public bool printView(string printName)
        {
            //打印
            Microsoft.Office.Interop.Word.Application app = null;
            Microsoft.Office.Interop.Word.Document    doc = null;
            object missing      = System.Reflection.Missing.Value;
            object templateFile = printFilePath;

            try
            {
                app = new Microsoft.Office.Interop.Word.ApplicationClass();
                doc = app.Documents.Add(ref templateFile, ref missing, ref missing, ref missing);

                //保存默认打印机
                string defaultPrint = app.ActivePrinter;
                app.ActivePrinter = printName;
                //预览
                app.Visible = true;
                doc.PrintPreview();
            }
            catch (Exception exp)
            {
                object saveChange = Microsoft.Office.Interop.Word.WdSaveOptions.wdPromptToSaveChanges;// .wdDoNotSaveChanges;
                if (doc != null)
                {
                    doc.Close(ref saveChange, ref missing, ref missing);
                }
                if (app != null)
                {
                    app.Quit(ref missing, ref missing, ref missing);
                }

                foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("WINWORD"))
                {
                    p.Kill();
                }

                return(false);
            }
            return(true);
        }
示例#22
0
        private void btnInDanhSach_Click(object sender, EventArgs e)
        {
            if (grvSVTrungTuyen.DataRowCount > 0)
            {
                Lib.clsExportToWord cls = new Lib.clsExportToWord();
                Microsoft.Office.Interop.Word.ApplicationClass WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                Microsoft.Office.Interop.Word.Document         aDoc    = null;
                cls.InitWord(WordApp, ref aDoc, 12);

                cls.AddText(aDoc, "Danh sách sinh viên trúng tuyển ", 1, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter, 16);

                cls.AddText(aDoc, "", 0, 0, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft, 12);

                cls.AddTable(aDoc, dtSinhVien, new string[] { "SBD", "Họ và tên", "Ngày sinh", "Giới tính", "Khối thi", "Ngành thi" },
                             new string[] { "SoBaoDanhTS", "HoVaTenTS", "NgaySinhTS", "GioiTinhTS", "KhoiThi", "NganhThi" });
                WordApp.Visible = true;
            }
            else
            {
                ThongBao("Chưa có danh sách sinh viên trúng tuyển.");
            }
        }
示例#23
0
        static void Main(string[] args)
        {
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            Object MISSING = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Document aDoc = null;
            aDoc            = wordApp.Documents.Open("D:\\SampleTemplate.docx");
            wordApp.Visible = false;
            FindAndReplace(wordApp, "<name>", "Test Name");
            wordApp.ActiveDocument.Characters.Last.Select();
            Microsoft.Office.Interop.Word.Selection selection = wordApp.Selection;
            Microsoft.Office.Interop.Word.Range     range     = selection.Range;
            Microsoft.Office.Interop.Word.Bookmarks bookmarks = aDoc.Bookmarks;
            int count = bookmarks.Count;

            Microsoft.Office.Interop.Word.Bookmark bookmark = bookmarks.Add("bookmark2", range);
            wordApp.Selection.Collapse();
            wordApp.Selection.TypeText("appended text........");
            aDoc.Save();
            aDoc.Close();
            Console.WriteLine("Hello World!");
        }
示例#24
0
        private void InsertUnloadFileToDocument(string bookmark, string documentLocation, string unloadLocation)
        {
            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();

            Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();

            //Full file name
            object objFileName = documentLocation;
            object visible     = false;
            object readOnly    = false;
            object IsSave      = true;

            object bookMarkName = bookmark;
            object oClassType   = "MSGraph.Chart";
            object oFileName    = unloadLocation;
            object oMissing     = System.Reflection.Missing.Value;
            object missingValue = System.Reflection.Missing.Value;

            try
            {
                //打开文件
                doc = WordApp.Documents.Open(ref objFileName, ref missingValue, ref readOnly, ref missingValue,
                                             ref missingValue, ref missingValue, ref missingValue, ref missingValue,
                                             ref missingValue, ref missingValue, ref missingValue, ref missingValue,
                                             ref missingValue, ref missingValue, ref missingValue,
                                             ref missingValue);
                doc.Activate();
                Microsoft.Office.Interop.Word.Bookmark titleBookmark = doc.Bookmarks.get_Item(ref bookMarkName);
                titleBookmark.Range.InlineShapes.AddOLEObject(ref oClassType, ref oFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                //doc. Close(ref IsSave, ref missingValue, ref missingValue);
            }
            finally
            {
                doc.Close(ref IsSave, ref missingValue, ref missingValue);
            }
        }
示例#25
0
        /// <summary>
        /// WORD文档处理
        /// </summary>
        /// <param name="strfilename">文件路径</param>
        void ForWord(string strfilename)
        {
            //建立Word类的实例,缺点:不能正确读取表格,图片等等的显示

            Microsoft.Office.Interop.Word.ApplicationClass app = new Microsoft.Office.Interop.Word.ApplicationClass();

            Microsoft.Office.Interop.Word.Document doc = null;

            object missing   = System.Reflection.Missing.Value;
            object FileName  = strfilename;
            object readOnly  = false;
            object isVisible = true;
            object index     = 0;

            try
            {
                doc = app.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);

                doc.ActiveWindow.Selection.WholeStory();
                doc.ActiveWindow.Selection.Copy();
                //从剪切板获取数据
                IDataObject data = Clipboard.GetDataObject();
                this.richTextBox1.Text = data.GetData(DataFormats.Text).ToString();
            }
            finally
            {
                if (app != null)
                {
                    app.Quit(ref missing, ref missing, ref missing);
                    app = null;
                }
            }
        }
示例#26
0
    public string wordToHtml(System.Web.UI.HtmlControls.HtmlInputFile wordFilePath)
    {
        Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
        Type wordType = word.GetType();
        Microsoft.Office.Interop.Word.Documents docs = word.Documents;
        // 打开文件
        Type docsType = docs.GetType();
        //应当先把文件上传至服务器然后再解析文件为html
        string filePath = uploadWord(wordFilePath);
        //判断是否上传文件成功
        if (filePath == "0")
            return "0";
        //判断是否为word文件
        if (filePath == "1")
            return "1";
        object fileName = filePath;
        Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open",
        System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { fileName, true, true });
        // 转换格式,另存为html
        Type docType = doc.GetType();
        string filename = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() +
        System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString();
        //被转换的html文档保存的位置
        string ConfigPath = HttpContext.Current.Server.MapPath("~/keyfile/a.html");
        object saveFileName = ConfigPath;

        docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
        null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML });
        //关闭文档
        docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod,
        null, doc, new object[] { null, null, null });
        // 退出 Word
        wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
        //转到新生成的页面
        return ("/" + filename + ".html");
    }
        /// <summary>
        /// 把Word文件转换成为PDF格式文件
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public static bool WordToPDF(string sourcePath, string targetPath)
        {
            targetPath = Regex.Replace(targetPath, " ", "", RegexOptions.IgnoreCase);//去除字符串中间的空格
            //bool result = false;
            Microsoft.Office.Interop.Word.WdExportFormat   exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
            Microsoft.Office.Interop.Word.ApplicationClass application  = null;

            Microsoft.Office.Interop.Word.Document document = null;
            try
            {
                bool TimeOver             = false; //转换时间到了
                System.Timers.Timer timer = new System.Timers.Timer(30000);
                timer.AutoReset = false;           //只循环一次
                timer.Elapsed  += delegate(object sender, System.Timers.ElapsedEventArgs e)
                {
                    TimeOver = true;
                };
                timer.Start();
                Thread th = new Thread(new ThreadStart(delegate()
                {
                    try
                    {
                        //document = application.Documents.Open(sourcePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, false, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                        application         = new Microsoft.Office.Interop.Word.ApplicationClass();
                        application.Visible = false;
                        document            = application.Documents.Open(sourcePath);
                        document.SaveAs();
                        document.ExportAsFixedFormat(targetPath, exportFormat);
                    }
                    catch
                    {
                    }
                }));
                th.IsBackground = true;//后台线程
                th.Start();
                //如果转换没有成功就一直循环
                while (th.ThreadState != System.Threading.ThreadState.Stopped)
                {
                    //如果一直没有转换成功,但是最大的转换时间到了也直接跳出While循环
                    if (TimeOver)
                    {
                        break;
                    }
                }
                if (th.ThreadState != System.Threading.ThreadState.Stopped)
                {
                    th.Abort();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                //result = false;
            }
            finally
            {
                if (document != null)
                {
                    document.Close();
                    document = null;
                }
                if (application != null)
                {
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            //判断文件是否转换成功
            if (File.Exists(targetPath))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
示例#28
0
文件: test.aspx.cs 项目: whuacn/CJia
        //上传文件并转换为html wordToHtml(wordFilePath)
        ///<summary>
        ///上传文件并转存为html
        ///</summary>
        ///<param name="wordFilePath">word文档在客户机的位置</param>
        ///<returns>上传的html文件的地址</returns>
        public string wordToHtml(System.Web.UI.HtmlControls.HtmlInputFile wordFilePath)
        {
            Alert.Show("hello");
            //txt_TitleName.Text = "12";
            Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
            Type wordType = word.GetType();

            Microsoft.Office.Interop.Word.Documents docs = word.Documents;
            // 打开文件
            Type docsType = docs.GetType();
            //应当先把文件上传至服务器然后再解析文件为html
            string filePath = uploadWord(wordFilePath);

            //判断是否上传文件成功
            if (filePath == "0")
            {
                return("0");
            }
            //判断是否为word文件
            if (filePath == "1")
            {
                return("1");
            }
            object fileName = filePath;

            Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open",
                                                                                                                       System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { fileName, true, true });
            // 转换格式,另存为html
            Type docType = doc.GetType();

            string filename = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() +
                              System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString();

            // 判断指定目录下是否存在文件夹,如果不存在,则创建
            string abc = Server.MapPath("~\\html");

            Alert.Show("html文件路径" + abc);
            //Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "alert(" + abc + ")", true);
            if (!Directory.Exists(Server.MapPath("~\\html")))
            {
                // 创建up文件夹
                Directory.CreateDirectory(Server.MapPath("~\\html"));
            }

            //被转换的html文档保存的位置
            string ConfigPath   = abc + "\\" + filename + ".html";
            object saveFileName = ConfigPath;

            /*下面是Microsoft Word 9 Object Library的写法,如果是10,可能写成:
             * docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
             * null, doc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML});
             * 其它格式:
             * wdFormatHTML
             * wdFormatDocument
             * wdFormatDOSText
             * wdFormatDOSTextLineBreaks
             * wdFormatEncodedText
             * wdFormatRTF
             * wdFormatTemplate
             * wdFormatText
             * wdFormatTextLineBreaks
             * wdFormatUnicodeText
             */
            docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
                                 null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML });
            //关闭文档
            docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod,
                                 null, doc, new object[] { null, null, null });
            // 退出 Word
            wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
            //转到新生成的页面
            return("/" + filename + ".html");
        }
    public bool ExportToWord(DataSet ds, string path1, string path2, string[] obDD)//说明ds为数据集,path1为模版路径,path2为生成文档的路径,obDD为末班里面的书签
    {
        Microsoft.Office.Interop.Word.Application appWord = null;
        Microsoft.Office.Interop.Word.Document doc = null;
        try
        {
            appWord = new Microsoft.Office.Interop.Word.ApplicationClass();
            appWord.Visible = false;
            object objTrue = true;
            object objFalse = false;
            object objTemplate = path1;//模板路径
            object objDocType = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument;
            doc = appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);
            //第一步生成word文档
            //定义书签变量
            int length=obDD.Length;
            object[] obDD_Name = new object[length];
            int j = 0;
           
            for (int i1 = 0; i1 < ds.Tables[0].Rows.Count; i1++)
            {
                for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                {
                    int total=i1*ds.Tables[0].Columns.Count+i+1;
                    if(length<total){
                        break;
                    }
                    obDD_Name[j] = obDD[j];
                    
                    doc.Bookmarks.get_Item(ref obDD_Name[j]).Range.Text = ds.Tables[0].Rows[i1][i].ToString(); //循环加入书签
                    j++;

                }
            }
           
            // ....
            //第四步 生成word
            object filename = path2;
            object miss = System.Reflection.Missing.Value;
            try
            {
                doc.SaveAs(ref filename, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                //doc.Visible = true;//测试

            }
            catch
            {
                // System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: " + DATAWORDPATH + tempFileName + WORDPOSTFIX);
                HttpContext.Current.Response.Write("<script>alert('系统找不到指定目录文件输出路径')<script>");
                return false;
            }
            object missingValue = Type.Missing;
            object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
            doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);//关闭WordDoc文档对象 
            //关闭WordApp组件对象 

            appWord.Application.Quit(ref miss, ref miss, ref miss);
            doc = null;
            appWord = null;
            return true;
           // HttpContext.Current.Response.Write("<script>alert('文档写入成功!')<script>");

        }
        catch (System.Exception a)
        {
            //捕捉异常,如果出现异常则清空实例,退出word,同时释放资源
            string aa = a.ToString();
            object miss = System.Reflection.Missing.Value;
            object missingValue = Type.Missing;
            object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
            doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
            appWord.Application.Quit(ref miss, ref miss, ref miss);
            doc = null;
            appWord = null;
            return false;
           // HttpContext.Current.Response.Write("<script>alert('向word文件中写入数据出错:" + a.Message + "')<script>");
        } 

    }
        public string SaveAs(string path)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.ApplicationClass();
            word.Visible = true;
            object fileName = Path.Combine(this.workingDirectory, this.tempFileName);

            Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(ref fileName);

            object saveTo = path;
            object fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault;
            doc.SaveAs2(ref saveTo, ref fileFormat);

            word.Documents.Close();

            //todo: Release the COM object.
            return saveTo as string;
        }
示例#31
0
        //Акты
        private void buttonAkt_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            wordApp.Visible = true;
            BringToFront();
            //System.IO.File.Copy(Application.StartupPath + "\\template_akt.doc", Application.StartupPath + "\\template_akt2.doc", true);
            Object documentPath = Application.StartupPath + "\\templates/template_akt.doc";
            Object confirmConversions = true;
            Object readOnly = true;
            Object addToRecentFiles = true;
            Object passwordDocument = Type.Missing;
            Object passwordTemplate = Type.Missing;
            Object revert = false;
            Object writePasswordDocument = Type.Missing;
            Object writePasswordTemplate = Type.Missing;
            Object format = Type.Missing;
            Object encoding = Type.Missing; ;
            Object oVisible = Type.Missing;
            Object openConflictDocument = Type.Missing;
            Object openAndRepair = Type.Missing;
            Object documentDirection = Type.Missing;
            Object noEncodingDialog = false;
            Object xmlTransform = Type.Missing;

            Microsoft.Office.Interop.Word.Document wordDocument = wordApp.Documents.Open(ref documentPath, ref confirmConversions, ref readOnly, ref addToRecentFiles,
              ref passwordDocument, ref passwordTemplate, ref revert,
              ref writePasswordDocument, ref writePasswordTemplate,
              ref format, ref encoding, ref oVisible,
              ref openAndRepair, ref documentDirection, ref noEncodingDialog, ref xmlTransform);
            object oBookMark = "fio";
            object oBookMark1 = "fio1";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = comboBoxEkskursovod.Text;
            wordDocument.Bookmarks.get_Item(ref oBookMark1).Range.Text = comboBoxEkskursovod.Text;
            oBookMark = "data";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = dateTimePicker2.Text;
            oBookMark = "date1";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = dateTimePicker1.Text;
            oBookMark = "date2";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = dateTimePicker2.Text;
            oBookMark = "koleks";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = getKol_eks();
            oBookMark = "sum";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = getSum();

            oBookMark = "sum1";
            decimal n = decimal.Parse(getSum());
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = NumByWords.RurPhrase(n);
        }
示例#32
0
 public WordHelp()
 {
     // activate the interface with the COM object of Microsoft Word
     oWordApplic = new Microsoft.Office.Interop.Word.ApplicationClass();
 }
    public void ExportToWord(DataSet ds)
    {


        
        if (ds.Tables.Count>0)
        {
            string tempFileName = "临时的";
            object filename = null;

            object tableBehavior = Microsoft.Office.Interop.Word.WdDefaultTableBehavior.wdWord9TableBehavior;
            object autoFitBehavior = Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitFixed;

            object unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
            object extend = System.Reflection.Missing.Value;
            object breakType = (int)Microsoft.Office.Interop.Word.WdBreakType.wdSectionBreakNextPage;

            object count = 1;
            object character = Microsoft.Office.Interop.Word.WdUnits.wdCharacter;

            object Nothing = System.Reflection.Missing.Value;

            try
            {
                //tempFileName = GetTempFileName();

                //生成.doc文件完整路径名 
                filename ="112.doc";

                //创建一个word文件,文件名用系统时间生成精确到毫秒 
                Microsoft.Office.Interop.Word.Application myWord = new Microsoft.Office.Interop.Word.ApplicationClass();
                Microsoft.Office.Interop.Word.Document myDoc = new Microsoft.Office.Interop.Word.DocumentClass();
                myDoc = myWord.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                myDoc.Activate();

                //向把dataset中的表插入到word的文件中 

                for (int totalTable = 0; totalTable < ds.Tables.Count; totalTable++)
                {
                    myWord.Application.Selection.TypeText(ds.Tables[totalTable].TableName + "表的数据如下");
                    myWord.Application.Selection.TypeParagraph();
                    myWord.Application.Selection.TypeParagraph();
                    Microsoft.Office.Interop.Word.Range para = myWord.Application.Selection.Range;
                    myDoc.Tables.Add(para, ds.Tables[totalTable].Rows.Count + 1, ds.Tables[totalTable].Columns.Count, ref tableBehavior, ref autoFitBehavior);
                    for (int column = 0; column < ds.Tables[totalTable].Columns.Count; column++)
                    {
                        myDoc.Tables[0].Cell(1, column + 1).Range.InsertBefore(ds.Tables[0].Columns[column].ColumnName.Trim());

                    }
                    for (int row = 0; row < ds.Tables[totalTable].Rows.Count; row++)
                    {
                        for (int column = 0; column < ds.Tables[totalTable].Columns.Count; column++)
                        {
                            myDoc.Tables[1].Cell(row + 2, column + 1).Range.InsertBefore(ds.Tables[totalTable].Rows[row][column].ToString().Trim());
                        }
                    }
                    myWord.Application.Selection.EndKey(ref unit, ref extend);
                    myWord.Application.Selection.TypeParagraph();
                    myWord.Application.Selection.TypeParagraph();
                    myWord.Application.Selection.InsertBreak(ref breakType);
                }
                myWord.Application.Selection.TypeBackspace();
                myWord.Application.Selection.Delete(ref character, ref count);
                myWord.Application.Selection.HomeKey(ref unit, ref extend);
                //保存word文件到指定的目录下 
                try
                {
                    myDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                    myWord.Visible = true;
                    object missingValue = Type.Missing;
                    object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
                    myDoc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
                    object miss = System.Reflection.Missing.Value;
                    myDoc.Application.Quit(ref miss, ref miss, ref miss);
                    // doc = null;
                    myWord = null;

                }
                catch
                {
                    // System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: " + DATAWORDPATH + tempFileName + WORDPOSTFIX);
                    HttpContext.Current.Response.Write("<script>alert('系统找不到指定目录下的文件:" + DATAWORDPATH + tempFileName + WORDPOSTFIX + "')<script>");
                    return;
                }
               

                //让生成的word文件可见 
              //  myWord.Visible = true;
            }
            catch (Exception ex)
            {
                //   System.Windows.Forms.MessageBox.Show("向word文件中写入数据出错: " + ex.Message);
                HttpContext.Current.Response.Write("<script>alert('向word文件中写入数据出错:" + ex.Message + "')<script>");
            }
        }
        else
        {
            //   System.Windows.Forms.MessageBox.Show("No Data");
            HttpContext.Current.Response.Write("<script>alert('没有数据。')<script>");

        }
    }
示例#34
0
        /// <summary>
        /// Word转换成pdf
        /// </summary>
        /// <param name="sourcePath">源文件路径(物理路径)</param>
        /// <param name="targetPath">目标文件路径(物理路径)</param>
        /// <returns>true=转换成功</returns>
        public static bool DOCConvertToPDF(string sourcePath, string targetPath)
        {
            //    string targetPath = "G:\\工作\\ceshi\\ceshi.pdf";
            //    sourcePath = "G:\\工作\\OfficePreview\\Preview\\SourceFile\\测试.doc";
            bool result = false;

            Microsoft.Office.Interop.Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
            object paramMissing = Type.Missing;

            Microsoft.Office.Interop.Word.ApplicationClass wordApplication = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word._Document        wordDocument    = null;
            try
            {
                object paramSourceDocPath  = sourcePath;
                string paramExportFilePath = targetPath;
                Microsoft.Office.Interop.Word.WdExportFormat paramExportFormat = exportFormat;
                bool paramOpenAfterExport = false;
                Microsoft.Office.Interop.Word.WdExportOptimizeFor paramExportOptimizeFor = Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
                Microsoft.Office.Interop.Word.WdExportRange       paramExportRange       = Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage   = 0;
                Microsoft.Office.Interop.Word.WdExportItem paramExportItem = Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM         = true;
                Microsoft.Office.Interop.Word.WdExportCreateBookmarks paramCreateBookmarks = Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags   = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1      = false;
                wordDocument = wordApplication.Documents.Open(
                    ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing);
                if (wordDocument != null)
                {
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                     paramExportFormat, paramOpenAfterExport,
                                                     paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                     paramEndPage, paramExportItem, paramIncludeDocProps,
                                                     paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                     paramBitmapMissingFonts, paramUseISO19005_1,
                                                     ref paramMissing);
                }
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordDocument = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordApplication = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return(result);
        }
示例#35
0
 public static void PrintWord(string targetFile, byte[] docBytes, DataTable dataSource, bool preview, PrintBySelf printByself, FormatColumnValue formatColumnValue, bool write)
 {
     BackgroundWorker worker = new BackgroundWorker();
     worker.DoWork += delegate (object sender, DoWorkEventArgs e) {
         WaitDialogHelper.Show();
         try
         {
             object fileName = targetFile;
             object readOnly = false;
             object visible = true;
             object confirmConversions = Missing.Value;
             if (LoggingService.IsInfoEnabled)
             {
                 LoggingService.Info("准备写临时WORD文件");
             }
             File.WriteAllBytes((string) fileName, docBytes);
             Microsoft.Office.Interop.Word.Application oWordApplic = new Microsoft.Office.Interop.Word.ApplicationClass();
             Microsoft.Office.Interop.Word.Document doc = oWordApplic.Documents.Open(ref fileName, ref confirmConversions, ref readOnly, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref visible, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref confirmConversions);
             Microsoft.Office.Interop.Word.Bookmarks bookmarks = doc.Bookmarks;
             foreach (Microsoft.Office.Interop.Word.Bookmark bookmark in bookmarks)
             {
                 string text = string.Empty;
                 if (LoggingService.IsInfoEnabled)
                 {
                     LoggingService.InfoFormatted("Word标签:{0}", new object[] { bookmark.Name });
                 }
                 bool flag = false;
                 try
                 {
                     if (printByself != null)
                     {
                         flag = printByself(bookmark.Name, ref text);
                     }
                 }
                 catch (Exception exception)
                 {
                     LoggingService.Error(exception);
                 }
                 if (!flag && dataSource.Columns.Contains(bookmark.Name))
                 {
                     if (formatColumnValue != null)
                     {
                         text = formatColumnValue(dataSource.Rows[0][bookmark.Name], dataSource.Columns[bookmark.Name].DataType, bookmark.Name);
                     }
                     else
                     {
                         text = dataSource.Rows[0][bookmark.Name].ToString();
                     }
                     flag = true;
                 }
                 if (flag)
                 {
                     bookmark.Range.Text = text;
                 }
             }
             doc.Fields.Update();
             ShowOrPrintDocumnet(preview, write, ref confirmConversions, ref oWordApplic, ref doc);
         }
         finally
         {
             WaitDialogHelper.Close();
         }
     };
     worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(PrintHelper.RunPrintWordWorkerCompleted);
     worker.RunWorkerAsync();
 }
示例#36
0
        public void downTable()
        {
            try
            {
                var direc = HttpContext.Current.Server.MapPath(HttpPostedFileExtension.POSTED_FILE_ROOT_DIRECTORY);
                //@"D:\member\wanghuanjun\Ipms\Solution\0.3\Ipms.WebSite\IpmsDocument\
                var templateName = direc + "附件1-985大型设备购置论证报告_模板.doc";
                Microsoft.Office.Interop.Word.ApplicationClass wordApp;
                Microsoft.Office.Interop.Word.Document wordDocument = new Microsoft.Office.Interop.Word.Document();
                object Obj_FileName = templateName;
                object Visible = false;
                object ReadOnly = false;
                object missing = System.Reflection.Missing.Value;
                wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                Object Nothing = System.Reflection.Missing.Value;
                wordDocument = wordApp.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref Visible,
                    ref missing, ref missing, ref missing,
                    ref missing);
                wordDocument.Activate();

                Microsoft.Office.Interop.Word.Table wordTable = wordDocument.Tables[1];

                var Iid = Request.GetInt("tastItemID");

                var memI = Database.ConstructTaskItems.SingleOrDefault(cti => cti.ID == Iid);

                wordDocument.Bookmarks.get_Item("DeviceName").Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName;
                wordDocument.Bookmarks.get_Item("Unit").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Project.College.Name;
                wordDocument.Bookmarks.get_Item("DeviceManager").Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Member.Name;
                wordDocument.Bookmarks.get_Item("Phone").Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Member.GetExpert(Database).MobilePhone;
                wordDocument.Bookmarks.get_Item("Year").Range.Text = DateTime.Now.Year.ToString();
                wordDocument.Bookmarks.get_Item("month").Range.Text = DateTime.Now.Month.ToString();
                wordDocument.Bookmarks.get_Item("day").Range.Text = DateTime.Now.Day.ToString();
                wordDocument.Bookmarks.get_Item("year2").Range.Text = DateTime.Now.Year.ToString();
                wordDocument.Bookmarks.get_Item("month2").Range.Text = DateTime.Now.Month.ToString();
                //wordDocument.Bookmarks.get_Item("Manager").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Project.Manager.Name;
                //wordDocument.Bookmarks.get_Item("DeviceNumber").Range.Text = memI.ConstructPlanItem.DeviceNumber;

                wordTable.Cell(1, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName;
                wordTable.Cell(2, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.EnglishName;
                wordTable.Cell(3, 4).Range.Text = memI.ConstructPlanItem.MemberApplyItem.Quantity.ToString();
                wordTable.Cell(3, 2).Range.Text = (memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice / 100).ToString() + "元";
                wordTable.Cell(3, 6).Range.Text = ((memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice * memI.ConstructPlanItem.MemberApplyItem.Quantity) / 100).ToString() + "元";

                wordDocument.Bookmarks.get_Item("NecessityAnalysis").Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.NecessityAnalysis;
                wordTable.Cell(5, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.MainSpec;

                SaveDocument(wordDocument, wordApp, direc + "大型设备购置论证报告.doc");

                downLoad(direc + "大型设备购置论证报告.doc", "大型设备购置论证报告.doc");

                var downLoadInfo = string.Format("{0}下载设备:{1},购置论证报告", User.Name, memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName);
                BusinessLog.Write(User, Request.UserHostAddress, downLoadInfo, Database);
            }
            catch (System.Exception ex)
            {
                new PackedException("大型设备购置论证报告", ex).Hanldle();
            }
        }
示例#37
0
        public void toolSubItem_MouseOver(object sender, EventArgs e)
        {
            string myNewStrings = ((ToolStripMenuItem)sender).Text;
              DirectoryInfo directoryInfo= new DirectoryInfo(@"C:\MyData\MyTemplate\");
              string IOPath= directoryInfo.ToString()+myNewStrings+".rtf";

              string allText = string.Empty;
              Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
              string filename = IOPath;
              object file = filename;

              object nullobj = System.Reflection.Missing.Value;

              Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref file, 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.ActiveWindow.Selection.WholeStory();
              IDataObject data = Clipboard.GetDataObject();
              Clipboard.Clear();
              doc.ActiveWindow.Selection.Copy();
              doc.Close(ref nullobj, ref nullobj, ref nullobj);
              wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);
        }
示例#38
0
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        WordFileToRead.SaveAs(Server.MapPath(WordFileToRead.FileName));
        object filename = Server.MapPath(WordFileToRead.FileName);

        Microsoft.Office.Interop.Word.ApplicationClass AC  = new Microsoft.Office.Interop.Word.ApplicationClass();
        Microsoft.Office.Interop.Word.Document         doc = new Microsoft.Office.Interop.Word.Document();
        object readOnly  = false;
        object isVisible = true;
        object missing   = System.Reflection.Missing.Value;

        try
        {
            doc = AC.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 isVisible, ref missing, ref missing, ref missing);

            StringReader sr = new StringReader(doc.Content.Text);

            string[] NameSurname1 = doc.Content.Text.Split('\r');

            string fullname = NameSurname1[0];

            string[] name = fullname.Split();
            if (name.Length == 3)
            {
                txtFname.Text = name[0];
                txtLname.Text = name[2];
            }
            else
            {
                txtFname.Text = name[0];
                txtLname.Text = name[1];
            }

            const string MatchPhonePattern = @"\(?\d{3}\)?-? *\d{3}-? *-?\d{4}";
            Regex        rx = new Regex(MatchPhonePattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            // Find matches.
            MatchCollection matches = rx.Matches(doc.Content.Text);
            // Report the number of matches found.
            int noOfMatches = matches.Count;
            // Report on each match.
            //  string tempPhoneNumbers = "";
            foreach (Match match in matches)
            {
                txtphoneNo.Text = txtphoneNo.Text + match.Value.ToString();
            }

            const string MatchEmailPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            Regex        rx1 = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            // Find matches.
            MatchCollection matches1 = rx1.Matches(doc.Content.Text);
            // Report the number of matches found.
            int noOfMatches1 = matches1.Count;
            // Report on each match.
            string tempemail = "";
            foreach (Match match1 in matches1)
            {
                txtEmail.Text = txtEmail.Text + match1.Value.ToString();
            }

            const string Zipcode   = @"\d{5}";
            Regex        rxzipcode = new Regex(Zipcode, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            // Find matches.
            MatchCollection matcheszip = rxzipcode.Matches(doc.Content.Text);
            // Report the number of matches found.
            int mat = matcheszip.Count;
            // Report on each match.
            foreach (Match match2 in matcheszip)
            {
                txtZip.Text = txtZip.Text + match2.Value.ToString();
            }
        }
        catch (Exception ex)
        {
        }
    }
    public bool ExportToWord(DataSet ds, string path1, string path2, string[] obDD)//说明ds为数据集,path1为模版路径,path2为生成文档的路径,obDD为末班里面的书签
    {
        Microsoft.Office.Interop.Word.Application appWord = null;
        Microsoft.Office.Interop.Word.Document doc = null;
        try
        {
            appWord = new Microsoft.Office.Interop.Word.ApplicationClass();
            appWord.Visible = false;
            object objTrue = true;
            object objFalse = false;
            object objTemplate = path1;//模板路径
            object objDocType = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument;
            doc = appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);
            //第一步生成word文档
            //定义书签变量
            int length=obDD.Length;
            object[] obDD_Name = new object[length];

            for (int i = 0; i < obDD.Length; i++)
            {
                obDD_Name[i]=obDD[i];
               
                doc.Bookmarks.get_Item(ref obDD_Name[i]).Range.Text = ds.Tables[0].Rows[0][i].ToString(); //姓 名
               // object obDD_Name = "t1";//姓 名
                //object obDD_Sex = "t2";//性 别
                //object obDD_Age = "t3";//年龄
                // object obDD_Birthday = "DD_Birthday"; //出生年月
                // object obDD_Nation = "DD_Nation"; //民 族
                // object obDD_Native = "DD_Native"; //籍 贯
                // ...
                //第二步 读取数据,填充数据集
                // SqlDataReader dr = XXXXX;//读取出来的数据集
                //第三步 给书签赋值
                //给书签赋值
             //   doc.Bookmarks.get_Item(ref obDD_Name).Range.Text = "nihao"; //姓 名
               // doc.Bookmarks.get_Item(ref obDD_Sex).Range.Text = "性 别";//性 别
               // doc.Bookmarks.get_Item(ref obDD_Age).Range.Text = Convert.ToString(DateTime.Now.Year);//年龄
            }
           // ds.Clear();
            // ....
            //第四步 生成word
            //object filename = Server.MapPath("file") + "\\" + "接收毕业生情况表" + ".doc";
            object filename = path2;
            object miss = System.Reflection.Missing.Value;
            try
            {
                doc.SaveAs(ref filename, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                //doc.Visible = true;//测试

            }
            catch
            {
                // System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: " + DATAWORDPATH + tempFileName + WORDPOSTFIX);
                HttpContext.Current.Response.Write("<script>alert('系统找不到指定目录文件输出路径')<script>");
                return false;
            }
            object missingValue = Type.Missing;
            object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
            doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
            appWord.Application.Quit(ref miss, ref miss, ref miss);
            doc = null;
            appWord = null;
            return true;
           // HttpContext.Current.Response.Write("<script>alert('文档写入成功!')<script>");

        }
        catch (System.Exception a)
        {
            //捕捉异常,如果出现异常则清空实例,退出word,同时释放资源
            string aa = a.ToString();
            object miss = System.Reflection.Missing.Value;
            object missingValue = Type.Missing;
            object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
            doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
            appWord.Application.Quit(ref miss, ref miss, ref miss);
            doc = null;
            appWord = null;
            return false;
           // HttpContext.Current.Response.Write("<script>alert('向word文件中写入数据出错:" + a.Message + "')<script>");
        } 

    }
示例#40
0
    protected void Button2_Click(object sender, EventArgs e)
    {
        SQLtoWord SW = new SQLtoWord();

        Button2.Enabled = false;

        string  str = "SELECT mt.[year], mt.Depart, mt.[time], mt.teacher_Name, mt.specify, mt.guiNum, mt.IsOne,mt.IsTaskGive, mt.IsrefRead, mt.IsGuided, mt.totalsituation, ms.student_Name, ms.title, ms.kind AS kind, ms.Ischanged, ms.IsReq, ms.IsCom, ms.Attitude, ms.quality, ms.result, mt.QA FROM midCheckForTea mt CROSS JOIN midCheckForStu ms where mt.teacher_ID='" + Session["username"] + "' and mt.year='" + Session["year"] + "'and ms.student_ID='" + Session["student_ID"] + "'";
        DB      db  = new DB();
        DataSet ds  = db.Select(str, db.DBconn());

        try
        {
            string tex   = ds.Tables[0].Rows[0][1].ToString();
            string path1 = Server.MapPath(@"..\\过程文档\\文档模版\\中期检查.doc");
            string path2 = Server.MapPath("..\\过程文档\\中期检查") + "\\" + Session["student_ID"] + this.Label6.Text + "中期检查表.doc";
            if (ds.Tables[0].Rows[0]["kind"].Equals("理论研究"))
            {
                ds.Tables[0].Rows[0]["kind"] = "√理论研究    □应用研究    □技术开发    □其他( )";
            }
            else if (ds.Tables[0].Rows[0]["kind"].Equals("应用研究"))
            {
                ds.Tables[0].Rows[0]["kind"] = "□理论研究    √应用研究    □技术开发    □其他( )";
            }
            else if (ds.Tables[0].Rows[0]["kind"].Equals("技术开发"))
            {
                ds.Tables[0].Rows[0]["kind"] = "□理论研究    □应用研究    √技术开发    □其他( )";
            }
            else
            {
                ds.Tables[0].Rows[0]["kind"] = "□理论研究    □应用研究    □技术开发    √其他(" + ds.Tables[0].Rows[0]["kind"] + ")";
            }



            Microsoft.Office.Interop.Word.Application appWord = null;
            Microsoft.Office.Interop.Word.Document    doc     = null;
            try
            {
                appWord         = new Microsoft.Office.Interop.Word.ApplicationClass();
                appWord.Visible = false;
                object objTrue     = true;
                object objFalse    = false;
                object objTemplate = path1;//模板路径
                object objDocType  = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument;
                doc = appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);
                //第一步生成word文档
                //定义书签变量
                object[] obDD = new object[36];
                obDD[0]  = "year";
                obDD[1]  = "Depart";
                obDD[2]  = "time";
                obDD[3]  = "teacher_Name";
                obDD[4]  = "specify";
                obDD[5]  = "guiNum";
                obDD[6]  = "IsOne";
                obDD[7]  = "IsTaskGive";
                obDD[8]  = "IsrefRead";
                obDD[9]  = "IsGuided";
                obDD[10] = "totalsituation";
                obDD[11] = "student_Name1";
                obDD[12] = "student_Name2";
                obDD[13] = "title";
                obDD[14] = "kind1";
                obDD[15] = "kind2";
                obDD[16] = "kind3";
                obDD[17] = "Ischanged";
                obDD[18] = "IsReq";
                obDD[19] = "IsCom1";
                obDD[20] = "IsCom2";
                obDD[21] = "IsCom3";
                obDD[22] = "IsCom4";
                obDD[23] = "Attitude1";
                obDD[24] = "Attitude2";
                obDD[25] = "Attitude3";
                obDD[26] = "Attitude4";
                obDD[27] = "quality1";
                obDD[28] = "quality2";
                obDD[29] = "quality3";
                obDD[30] = "quality4";
                obDD[31] = "result1";
                obDD[32] = "result2";
                obDD[33] = "result3";
                obDD[34] = "result4";
                obDD[35] = "QA";
                for (int i = 0; i < 12; i++)
                {
                    doc.Bookmarks.get_Item(ref obDD[i]).Range.Text = ds.Tables[0].Rows[0][i].ToString();
                }
                doc.Bookmarks.get_Item(ref obDD[12]).Range.Text = ds.Tables[0].Rows[0][11].ToString();
                doc.Bookmarks.get_Item(ref obDD[13]).Range.Text = ds.Tables[0].Rows[0][12].ToString();
                //前13个循环加入书签,第13个开始要进行字符处理
                //14个是kind
                string   str1   = ds.Tables[0].Rows[0][13].ToString();
                string[] sArray = str1.Split('√');

                doc.Bookmarks.get_Item(ref obDD[14]).Range.Text = sArray[0]; //加入书签

                doc.Bookmarks.get_Item(ref obDD[15]).Range.Text = "";        //加入书签

                doc.Bookmarks.get_Item(ref obDD[16]).Range.Text = sArray[1]; //加入书签

                // 15,16,个是 ms.Ischanged,ms.IsReq
                doc.Bookmarks.get_Item(ref obDD[17]).Range.Text = ds.Tables[0].Rows[0][14].ToString();
                doc.Bookmarks.get_Item(ref obDD[18]).Range.Text = ds.Tables[0].Rows[0][15].ToString();
                //17个是 ms.IsCom
                if (ds.Tables[0].Rows[0][16].Equals("提前完成"))
                {
                    doc.Bookmarks.get_Item(ref obDD[19]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[20]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[21]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[22]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][16].Equals("按计划完成"))
                {
                    doc.Bookmarks.get_Item(ref obDD[20]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[19]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[21]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[22]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][16].Equals("延期完成"))
                {
                    doc.Bookmarks.get_Item(ref obDD[21]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[19]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[20]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[22]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][16].Equals("没有完成"))
                {
                    doc.Bookmarks.get_Item(ref obDD[22]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[19]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[21]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[20]).Range.Text = "  ";
                }

                //18个是ms.Attitude
                if (ds.Tables[0].Rows[0][17].Equals("认真"))
                {
                    doc.Bookmarks.get_Item(ref obDD[23]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[24]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[25]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[26]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][17].Equals("较认真"))
                {
                    doc.Bookmarks.get_Item(ref obDD[24]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[23]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[25]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[26]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][17].Equals("一般"))
                {
                    doc.Bookmarks.get_Item(ref obDD[25]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[24]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[23]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[26]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][17].Equals("不认真"))
                {
                    doc.Bookmarks.get_Item(ref obDD[26]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[24]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[25]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[23]).Range.Text = "  ";
                }

                //19个是ms.result
                if (ds.Tables[0].Rows[0][18].Equals("优"))
                {
                    doc.Bookmarks.get_Item(ref obDD[27]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[28]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[29]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[30]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][18].Equals("良"))
                {
                    doc.Bookmarks.get_Item(ref obDD[28]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[27]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[29]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[30]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][18].Equals("中"))
                {
                    doc.Bookmarks.get_Item(ref obDD[29]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[28]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[27]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[30]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][18].Equals("差"))
                {
                    doc.Bookmarks.get_Item(ref obDD[30]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[28]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[29]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[27]).Range.Text = "  ";
                }

                //20个是ms.result
                if (ds.Tables[0].Rows[0][19].Equals("表扬"))
                {
                    doc.Bookmarks.get_Item(ref obDD[31]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[32]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[33]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[34]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][19].Equals("通过"))
                {
                    doc.Bookmarks.get_Item(ref obDD[32]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[31]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[33]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[34]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][19].Equals("警告"))
                {
                    doc.Bookmarks.get_Item(ref obDD[33]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[32]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[31]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[34]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][19].Equals("严重警告"))
                {
                    doc.Bookmarks.get_Item(ref obDD[34]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[32]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[33]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[31]).Range.Text = "  ";
                }
                //21个是mt.QA

                doc.Bookmarks.get_Item(ref obDD[35]).Range.Text = ds.Tables[0].Rows[0][20].ToString();


                //第四步 生成word
                object filename = path2;
                object miss     = System.Reflection.Missing.Value;
                try
                {
                    doc.SaveAs(ref filename, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                    //doc.Visible = true;//测试
                }
                catch
                {
                    // System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: " + DATAWORDPATH + tempFileName + WORDPOSTFIX);
                    Response.Write("<script>alert('系统找不到指定目录文件输出路径')<script>");
                }
                object missingValue     = Type.Missing;
                object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
                doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);//关闭WordDoc文档对象
                //关闭WordApp组件对象

                appWord.Application.Quit(ref miss, ref miss, ref miss);
                doc     = null;
                appWord = null;
                // Response.Write("<script>alert('文档写入成功!')<script>");
                //yi流的方式传送给客户端
                String             filepath = path2;
                System.IO.FileInfo file     = new System.IO.FileInfo(filepath);
                Response.Clear();
                Response.Charset         = "GB2312";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                // 添加头信息,为"文件下载/另存为"对话框指定默认文件名
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
                // 添加头信息,指定文件大小,让浏览器能够显示下载进度
                Response.AddHeader("Content-Length", file.Length.ToString());

                // 指定返回的是一个不能被客户端读取的流,必须被下载
                Response.ContentType = "application/ms-excel";

                // 把文件流发送到客户端
                Response.WriteFile(file.FullName);
                // 停止页面的执行
                Response.End();
            }
            catch (System.Exception a)
            {
                //捕捉异常,如果出现异常则清空实例,退出word,同时释放资源
                string aa               = a.ToString();
                object miss             = System.Reflection.Missing.Value;
                object missingValue     = Type.Missing;
                object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
                doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
                appWord.Application.Quit(ref miss, ref miss, ref miss);
                doc     = null;
                appWord = null;
                Response.Write("<script>alert('向word文件中写入数据出错。');location='midCheckEA.aspx'</script>");

                return;
            }
        }
        catch
        {
            Response.Write("<script>alert('数据库出错,您可能还未提交中期检查表.');location='midCheckEA.aspx'</script>");
            return;
        }
        finally
        {
            ds.Clear();
            Button2.Enabled = true;
        }
    }
示例#41
0
 public static void PrintWord(string file, bool preview, bool write)
 {
     DoWorkEventHandler handler = null;
     if (File.Exists(file))
     {
         BackgroundWorker worker = new BackgroundWorker();
         if (handler == null)
         {
             handler = delegate (object sender, DoWorkEventArgs e) {
                 WaitDialogHelper.Show();
                 try
                 {
                     object fileName = file;
                     object readOnly = false;
                     object visible = true;
                     object confirmConversions = Missing.Value;
                     Microsoft.Office.Interop.Word.Application oWordApplic = new Microsoft.Office.Interop.Word.ApplicationClass();
                     Microsoft.Office.Interop.Word.Document doc = oWordApplic.Documents.Open(ref fileName, ref confirmConversions, ref readOnly, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref visible, ref confirmConversions, ref confirmConversions, ref confirmConversions, ref confirmConversions);
                     ShowOrPrintDocumnet(preview, write, ref confirmConversions, ref oWordApplic, ref doc);
                 }
                 finally
                 {
                     WaitDialogHelper.Close();
                 }
             };
         }
         worker.DoWork += handler;
         worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(PrintHelper.RunPrintWordWorkerCompleted);
         worker.RunWorkerAsync();
     }
 }
示例#42
0
 public WordHelp(Microsoft.Office.Interop.Word.ApplicationClass wordapp)
 {
     oWordApplic = wordapp;
 }
示例#43
0
        public void s()
        {
            try
            {
                var direc = HttpContext.Current.Server.MapPath(HttpPostedFileExtension.POSTED_FILE_ROOT_DIRECTORY);
                //@"D:\member\wanghuanjun\Ipms\Solution\0.3\Ipms.WebSite\IpmsDocument\
                var templateName = direc + "大型精密仪器设备论证一览表_模板.doc";
                Microsoft.Office.Interop.Word.ApplicationClass wordApp;
                Microsoft.Office.Interop.Word.Document wordDocument = new Microsoft.Office.Interop.Word.Document();
                object Obj_FileName = templateName;
                object Visible = false;
                object ReadOnly = false;
                object missing = System.Reflection.Missing.Value;
                wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                Object Nothing = System.Reflection.Missing.Value;
                wordDocument = wordApp.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref Visible,
                    ref missing, ref missing, ref missing,
                    ref missing);
                wordDocument.Activate();

                Microsoft.Office.Interop.Word.Table wordTable = wordDocument.Tables[1];

                var Iid = Request.GetInt("tastItemID");

                var memI = Database.ConstructTaskItems.SingleOrDefault(cti => cti.ID == Iid);
                wordDocument.Bookmarks.get_Item("Unit").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Project.College.Name;
                wordDocument.Bookmarks.get_Item("DeviceManager").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Member.Name;
                wordDocument.Bookmarks.get_Item("Manager").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Project.Manager.Name;
                wordDocument.Bookmarks.get_Item("DeviceNumber").Range.Text = memI.ConstructPlanItem.DeviceNumber;

                wordTable.Cell(1, 3).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName;
                wordTable.Cell(2, 3).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.EnglishName;
                wordTable.Cell(3, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.Quantity.ToString();
                wordTable.Cell(3, 4).Range.Text = (memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice / 100).ToString() + "元";
                wordTable.Cell(3, 6).Range.Text = ((memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice * memI.ConstructPlanItem.MemberApplyItem.Quantity) / 100).ToString() + "元";

                wordTable.Cell(5, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.NecessityAnalysis;
                wordTable.Cell(12, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.MainSpec;
                wordTable.Cell(27, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.AccessorySpec;

                wordTable.Cell(1, 6).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Environment;
                wordTable.Cell(7, 9).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Consumables;
                wordTable.Cell(9, 9).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Power;

                var deviceMaths = Database.DeviceMatchs.Where(dm => dm.ApplyDevice == memI.ConstructPlanItem.MemberApplyItem.ApplyDevice);
                var temp = 0;
                //设备选型
                if (deviceMaths.Count() > 0 && deviceMaths.Count() <= 4)
                    foreach (var item in deviceMaths)
                    {
                        if (item != null)
                        {
                            wordTable.Cell(2, 5 + temp).Range.Text = item.MarketDevice.MarketDeviceName;
                            wordTable.Cell(4, 8 + temp).Range.Text = item.MarketDevice.Model;

                            var deviceSupplier = Database.DeviceSuppliers.Where(ds => ds.DeviceMatch == item).FirstOrDefault();
                            if (deviceSupplier != null)
                            {
                                wordTable.Cell(6, 4 + temp).Range.Text = deviceSupplier.Supplier.Name;
                                wordTable.Cell(7, 4 + temp).Range.Text = deviceSupplier.ContactPerson + ":" + deviceSupplier.ContactPhone;
                                wordTable.Cell(8, 4 + temp).Range.Text = (deviceSupplier.Price / 100).ToString() + "元";
                                wordTable.Cell(9, 4 + temp).Range.Text = deviceSupplier.PriceSource == 0 ? "供应商" : "网络";
                            }
                        }
                        temp += 1;
                    }
                var extrals = Database.DeviceExtramurals.Where(de => de.ApplyDevice == memI.ConstructPlanItem.MemberApplyItem.ApplyDevice).ToList();
                if (extrals.Count() > 0 && extrals.Count() <= 4)
                {
                    if (extrals.Count() >= 1)
                    {
                        wordTable.Cell(11, 4).Range.Text = extrals[0].Brand.ToString();
                        wordTable.Cell(11, 5).Range.Text = extrals[0].WorkUnit.ToString();
                        wordTable.Cell(11, 6).Range.Text = extrals[0].UserName;
                        wordTable.Cell(11, 7).Range.Text = extrals[0].BuyTime.Value.ToShortDateString();
                        wordTable.Cell(11, 8).Range.Text = (extrals[0].UnitPrice / 100).ToString() + "元";
                        for (int i = 1; i < extrals.Count(); i++)
                        {
                            wordTable.Cell(11 + i, 4).Range.Text = extrals[i].Brand.ToString();
                            wordTable.Cell(11 + i, 5).Range.Text = extrals[i].WorkUnit.ToString();
                            wordTable.Cell(11 + i, 6).Range.Text = extrals[i].UserName;
                            wordTable.Cell(11 + i, 7).Range.Text = extrals[i].BuyTime.Value.ToShortDateString();
                            wordTable.Cell(11 + i, 8).Range.Text = (extrals[i].UnitPrice / 100).ToString() + "元";
                        }
                    }
                }

                SaveDocument(wordDocument, wordApp, direc + "大型精密仪器设备论证一览表.doc");

                downLoad(direc + "大型精密仪器设备论证一览表.doc", "大型精密仪器设备论证一览表.doc");

                var downLoadInfo = string.Format("国资处:{0},下载设备:{1} 的大型设备论证报告", User.Name, memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName);
                BusinessLog.Write(User, Request.UserHostAddress, downLoadInfo, Database);
            }
            catch (System.Exception ex)
            {
                new PackedException("导出大型精密仪器论证一览表", ex).Hanldle();
            }
        }
示例#44
0
        /*----------------
         *----------------
         *Договор
         */
        private void buttonDog_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            wordApp.Visible = true;
            BringToFront();
            //System.IO.File.Copy(Application.StartupPath + "\\template_dogovor.doc", Application.StartupPath + "\\template_dogovor2.doc", true);
            Object documentPath = Application.StartupPath + "\\templates/template_dogovor.doc";
            Object confirmConversions = true;
            Object readOnly = true;
            Object addToRecentFiles = true;
            Object passwordDocument = Type.Missing;
            Object passwordTemplate = Type.Missing;
            Object revert = false;
            Object writePasswordDocument = Type.Missing;
            Object writePasswordTemplate = Type.Missing;
            Object format = Type.Missing;
            Object encoding = Type.Missing; ;
            Object oVisible = Type.Missing;
            Object openConflictDocument = Type.Missing;
            Object openAndRepair = Type.Missing;
            Object documentDirection = Type.Missing;
            Object noEncodingDialog = false;
            Object xmlTransform = Type.Missing;

            Microsoft.Office.Interop.Word.Document wordDocument = wordApp.Documents.Open(ref documentPath, ref confirmConversions, ref readOnly, ref addToRecentFiles,
              ref passwordDocument, ref passwordTemplate, ref revert,
              ref writePasswordDocument, ref writePasswordTemplate,
              ref format, ref encoding, ref oVisible,
              ref openAndRepair, ref documentDirection, ref noEncodingDialog, ref xmlTransform);
            object oBookMark = "fio";
            object oBookMark1 = "fio1";
            string pass = "******";
            string rozh = "rozhd";
            string strax = "strax";
            string tel = "tel";
            string address = "address";
            string inn = "inn";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = comboBoxEkskursovod.Text;
            wordDocument.Bookmarks.get_Item(ref oBookMark1).Range.Text = comboBoxEkskursovod.Text;
            oBookMark = "pass";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = getPass(pass);
            oBookMark = "pass1";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = getPass(pass);
            oBookMark = "rozhd";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = getPass(rozh);
            oBookMark = "address";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = getPass(address);
            oBookMark = "inn";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = getPass(inn);
            oBookMark = "strax";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = getPass(strax);
            oBookMark = "tel";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = getPass(tel);
            oBookMark = "kat";
            wordDocument.Bookmarks.get_Item(ref oBookMark).Range.Text = getCategory().ToString();
        }
示例#45
0
        public void downOffice()
        {
            try
            {
                var direc = HttpContext.Current.Server.MapPath(HttpPostedFileExtension.POSTED_FILE_ROOT_DIRECTORY);
                //@"D:\member\wanghuanjun\Ipms\Solution\0.3\Ipms.WebSite\IpmsDocument\
                var templateName = direc + "办公室函件模板.doc";
                Microsoft.Office.Interop.Word.ApplicationClass wordApp;
                Microsoft.Office.Interop.Word.Document wordDocument = new Microsoft.Office.Interop.Word.Document();
                object Obj_FileName = templateName;
                object Visible = false;
                object ReadOnly = false;
                object missing = System.Reflection.Missing.Value;
                wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                Object Nothing = System.Reflection.Missing.Value;
                wordDocument = wordApp.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref Visible,
                    ref missing, ref missing, ref missing,
                    ref missing);
                wordDocument.Activate();

                var Oid = Request.GetInt("officeItemID");

                var OfficeBudgetDetail = Database.OfficeBudgetDetails.SingleOrDefault(cti => cti.ID == Oid);

                wordDocument.Bookmarks.get_Item("DocNumber").Range.Text = OfficeBudgetDetail.DocNumber;
                wordDocument.Bookmarks.get_Item("DocName").Range.Text = OfficeBudgetDetail.DocName;
                wordDocument.Bookmarks.get_Item("DocContent").Range.Text = OfficeBudgetDetail.DocContent;
                wordDocument.Bookmarks.get_Item("DocYear").Range.Text = OfficeBudgetDetail.ReportYear;
                wordDocument.Bookmarks.get_Item("DocSource").Range.Text = OfficeBudgetDetail.FundSource.ToString();
                wordDocument.Bookmarks.get_Item("Time").Range.Text = DateTime.Now.ToShortDateString();
                //var OfficeBudgetDetailItem = Database.OfficeBudgetDetailItems.SingleOrDefault(ctii => ctii.OfficeBudgetDetailID == Oid);
                //wordDocument.Bookmarks.get_Item("DocContactor").Range.Text = OfficeBudgetDetailItem.AssetFundApplyItem.ContractItem.BidResultItem.PurchaseOrderItem.PurchasePlanItem.ConstructTaskItem.ConstructPlanItem.MemberApplyItem.MemberApply.Project.Contactor.Name;
                //wordDocument.Bookmarks.get_Item("DocContactorPhone").Range.Text = OfficeBudgetDetailItem.AssetFundApplyItem.ContractItem.BidResultItem.PurchaseOrderItem.PurchasePlanItem.ConstructTaskItem.ConstructPlanItem.MemberApplyItem.MemberApply.Project.Contactor.MobilePhone;

                SaveDocument(wordDocument, wordApp, direc + "办公室函件.doc");

                downLoad(direc + "办公室函件.doc", "办公室函件.doc");

                var downLoadInfo = string.Format("{0}下载设备:{1},办公室函件", User.Name, OfficeBudgetDetail.Operator);
                BusinessLog.Write(User, Request.UserHostAddress, downLoadInfo, Database);
            }
            catch (System.Exception ex)
            {
                new PackedException("办公室函件", ex).Hanldle();
            }
        }
示例#46
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="intQCInfo_ID">质检编号</param>
        public void AddPrintDemoMethod()
        {
            #region 判断是否安装Word
            if (IsInstallWord() == false)
            {
                MessageBox.Show("请先安装Microsoft Office办公软件");
                return;
            }
            #endregion

            //#region 复制模版
            string file = Common.PrintDemoTitleRoute;//模板路径
            if (!Common.rbool)
            {
                file = Common.PrintDemoTitleRouteTemporary;
            }


            //string newWordFile = CopyWord(file);

            //#endregion

            #region 加载模版
            object oMissing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.ApplicationClass WordApp;
            Microsoft.Office.Interop.Word.Document         WordDoc;
            WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            object fileName = file;
            WordDoc = WordApp.Documents.Open(ref fileName, 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, ref oMissing);
            #endregion

            FindReplace(WordDoc, "[QCInfo_ID]", Common.intQCInfo_ID.ToString(), 0);
            List <string> sqlString = new List <string>();
            sqlString = GetTableSQL(WordDoc);          //获取表格数据的SQL语句


            #region 填充数据

            #region 标题
            if (Common.rboolBT)
            {
                FindReplace(WordDoc, "[标题]", Common.PrintDemoTitle, 0);            //查找指定字段并进行替换操作
            }
            else
            {
                FindReplace(WordDoc, "[标题]", Common.AbnormalPrintDemoTitle, 0);            //查找指定字段并进行替换操作
            }
            #endregion
            string strsql = "";
            #region 非表格字段的数据替换
            if (sqlString.Count >= 1 && WordDoc.Content.Tables.Count >= 1)
            {
                List <string> otherFields = new List <string>();
                otherFields = GetOtherFields(WordDoc);
                strsql      = sqlString[0];//.ElementAt(0);
                if (!string.IsNullOrEmpty(strsql))
                {
                    //strsql = String.Format("select * from View_QCInfo_InTerface where QCInfo_ID={0}", Common.intQCInfo_ID);
                    DataSet dsView_QCInfo_InTerface = LinQBaseDao.Query(strsql);
                    if (dsView_QCInfo_InTerface != null && dsView_QCInfo_InTerface.Tables[0].Rows.Count > 0)
                    {
                        for (int inti = 0; inti < dsView_QCInfo_InTerface.Tables[0].Rows.Count; inti++)
                        {
                            for (int i = 0; i < otherFields.Count; i++)
                            {
                                string oldtext = otherFields.ElementAt(i);
                                string txt     = otherFields.ElementAt(i);
                                if (dsView_QCInfo_InTerface.Tables[0].Rows[inti][txt] != null)
                                {
                                    string newtext = dsView_QCInfo_InTerface.Tables[0].Rows[inti][txt].ToString();
                                    if (newtext.Length < 12)
                                    {
                                        newtext = ISNullMethod(newtext, 12, 0);
                                    }
                                    if (IsDateTime(newtext))
                                    {
                                        newtext = newtext.Substring(0, 10);
                                    }
                                    FindReplace(WordDoc, "[" + oldtext + "]", newtext, 0);            //查找指定字段并进行替换操作
                                }
                            }
                        }
                    }
                    if (strsql != "")
                    {
                        FindReplace(WordDoc, "{" + strsql + "}", "", 0);
                    }
                }
            }

            #endregion

            DataSet ds  = new DataSet();
            DataSet ds1 = new DataSet();
            #region 拆包前水份
            if (sqlString.Count >= 2 && WordDoc.Content.Tables.Count >= 2)
            {
                int intTablesIndex = 2;
                strsql = sqlString[1];//.ElementAt(1);
                if (!string.IsNullOrEmpty(strsql))
                {
                    ds = LinQBaseDao.Query(strsql);
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        int RowNum    = ds.Tables[0].Rows.Count;
                        int ColumnNum = WordDoc.Content.Tables[intTablesIndex].Columns.Count;

                        //读模板
                        int r = 0;     //从第几行计算BlockColumn和IDColumn;
                        for (int i = 1; i <= WordDoc.Content.Tables[intTablesIndex].Rows.Count; i++)
                        {
                            for (int j = 1; j <= WordDoc.Content.Tables[intTablesIndex].Rows[i].Cells.Count; j++)
                            {
                                if (WordDoc.Content.Tables[intTablesIndex].Cell(i, j).Range.Text.Substring(0, WordDoc.Content.Tables[intTablesIndex].Cell(i, j).Range.Text.Length - 2) == "")
                                {
                                    r = i;
                                    break;
                                }
                            }
                            if (r != 0)
                            {
                                break;
                            }
                        }

                        int IDColumn = 0, BlockColumn = 0; //一行可以显示BlockColumn个数据
                        for (int i = 1; i <= WordDoc.Content.Tables[intTablesIndex].Columns.Count; i++)
                        {
                            if (WordDoc.Content.Tables[intTablesIndex].Cell(r, i).Range.Text.Substring(0, WordDoc.Content.Tables[intTablesIndex].Cell(r, i).Range.Text.Length - 2) != "")
                            {
                                IDColumn++;
                            }
                            else
                            {
                                BlockColumn++;
                            }
                        }

                        if (RowNum % BlockColumn != 0)
                        {
                            RowNum = RowNum / BlockColumn + 1;
                        }
                        else
                        {
                            RowNum = RowNum / BlockColumn;
                        }


                        for (int k = WordDoc.Content.Tables[intTablesIndex].Rows.Count + 1; k <= RowNum; k++)        //添加RowNum-1行
                        {
                            WordDoc.Content.Tables[intTablesIndex].Rows.Add(ref oMissing);
                            for (int c = 1; c <= WordDoc.Content.Tables[intTablesIndex].Columns.Count; c++)                                                                                              //初始化新添加行
                            {
                                string str = WordDoc.Content.Tables[intTablesIndex].Cell(k - 1, c).Range.Text.Substring(0, WordDoc.Content.Tables[intTablesIndex].Cell(k - 1, c).Range.Text.Length - 2); //获取表格原来的值
                                if (str == "")
                                {
                                    WordDoc.Content.Tables[intTablesIndex].Cell(k, c).Range.Text = str;
                                }
                                else
                                {
                                    int x = Convert.ToInt32(str);
                                    int y = Convert.ToInt32(IDColumn);
                                    WordDoc.Content.Tables[intTablesIndex].Cell(k, c).Range.Text = Convert.ToString(x + y);
                                }
                            }
                        }


                        /*往表里添加数据*/
                        int pRow = 1, qColumn = 1;
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            int    find = 1; //1表示没有找到填充格
                            string str  = WordDoc.Content.Tables[intTablesIndex].Cell(pRow, qColumn).Range.Text.Substring(0, WordDoc.Content.Tables[intTablesIndex].Cell(pRow, qColumn).Range.Text.Length - 2);
                            while (find == 1)
                            {
                                while (str == "")
                                {
                                    WordDoc.Content.Tables[intTablesIndex].Cell(pRow, qColumn).Range.Text = ds.Tables[0].Rows[i][0].ToString();
                                    find = 0;
                                    break;
                                }
                                qColumn++;
                                if (qColumn % WordDoc.Content.Tables[intTablesIndex].Columns.Count == 1)
                                {
                                    pRow++;
                                    qColumn = 1;
                                }
                                str = WordDoc.Content.Tables[intTablesIndex].Cell(pRow, qColumn).Range.Text.Substring(0, WordDoc.Content.Tables[intTablesIndex].Cell(pRow, qColumn).Range.Text.Length - 2);
                            }
                        }
                    }
                    if (strsql != "")
                    {
                        FindReplace(WordDoc, "{" + strsql + "}", "", 0);
                    }
                }
            }
            #endregion

            #region 拆包后水份和废纸包重量
            if (sqlString.Count >= 4 && WordDoc.Content.Tables.Count >= 3)
            {
                #region 拆包后水分模板

                int RowNum2 = 0;//行数
                // int ColumnNum2 = WordDoc.Content.Tables[3].Columns.Count;
                //读模板
                int r2 = 0;     //从第几行计算BlockColumn和IDColumn;
                for (int i = 1; i <= WordDoc.Content.Tables[3].Rows.Count; i++)
                {
                    for (int j = 1; j <= WordDoc.Content.Tables[3].Rows[i].Cells.Count; j++)
                    {
                        if (WordDoc.Content.Tables[3].Cell(i, j).Range.Text.Substring(0, WordDoc.Content.Tables[3].Cell(i, j).Range.Text.Length - 2) == "")
                        {
                            r2 = i;
                            break;
                        }
                    }
                    if (r2 != 0)
                    {
                        break;
                    }
                }
                int IDColumn2 = 1, BlockColumn2 = 1; //一行可以显示BlockColumn2个数据
                for (int i = 1; i <= WordDoc.Content.Tables[3].Columns.Count; i++)
                {
                    if (WordDoc.Content.Tables[3].Cell(r2, i).Range.Text.Substring(0, WordDoc.Content.Tables[3].Cell(r2, i).Range.Text.Length - 2) != "")
                    {
                        IDColumn2++;
                    }
                    else
                    {
                        BlockColumn2++;
                    }
                }
                #endregion
                #region 拆包后水份水分不为空
                //*************根据拆包后水份显示行数*******************************************************
                strsql = sqlString[3];//.ElementAt(2);
                if (!string.IsNullOrEmpty(strsql))
                {
                    ds = new DataSet();
                    ds = LinQBaseDao.Query(strsql);
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        RowNum2 = ds.Tables[0].Rows.Count;
                        if (RowNum2 % BlockColumn2 != 0)
                        {
                            RowNum2 = RowNum2 / BlockColumn2 + 1 + 1;   //因为第一行不显示数据,所以要多加一行
                        }
                        else
                        {
                            RowNum2 = RowNum2 / BlockColumn2 + 1;
                        }
                    }
                    if (strsql != "")
                    {
                        FindReplace(WordDoc, "{" + strsql + "}", "", 0);
                    }
                }
                //*************根据废纸包数显示行数*******************************************************
                string strsql1 = sqlString[2];//ElementAt(1);
                if (!string.IsNullOrEmpty(strsql1))
                {
                    ds1 = LinQBaseDao.Query(strsql1);
                    int intcount = ds1.Tables[0].Rows.Count;
                    if (RowNum2 > 0)                           //拆包后水份有数据
                    {
                        if (ds1 != null && intcount > RowNum2) //废纸包有数据
                        {
                            RowNum2 = ds1.Tables[0].Rows.Count;
                        }
                    }
                    else//拆包后水份无数据
                    {
                        if (ds1 != null && intcount > RowNum2)//废纸包有数据
                        {
                            RowNum2 = ds1.Tables[0].Rows.Count;
                            if (RowNum2 % BlockColumn2 != 0)
                            {
                                RowNum2 = RowNum2 / BlockColumn2 + 1 + 1;   //因为第一行不显示数据,所以要多加一行
                            }
                            else
                            {
                                RowNum2 = RowNum2 / BlockColumn2 + 1;
                            }
                        }
                    }
                    FindReplace(WordDoc, "{" + strsql1 + "}", "", 0);
                }
                //****************新添加拆包后水份和废纸包重量行数************************************************
                for (int k = WordDoc.Content.Tables[3].Rows.Count + 1; k <= RowNum2; k++)        //添加RowNum2-1行
                {
                    WordDoc.Content.Tables[3].Rows.Add(ref oMissing);
                    for (int c = 1; c <= WordDoc.Content.Tables[3].Columns.Count; c++)                                                                                 //初始化新添加行
                    {
                        string str = WordDoc.Content.Tables[3].Cell(k - 1, c).Range.Text.Substring(0, WordDoc.Content.Tables[3].Cell(k - 1, c).Range.Text.Length - 2); //获取表格原来的值
                        if (str == "")
                        {
                            WordDoc.Content.Tables[3].Cell(k, c).Range.Text = str;
                        }
                        else
                        {
                            if (c == 2)
                            {
                                WordDoc.Content.Tables[3].Cell(k, c).Range.Text = str;
                            }
                            else if (c == 1)
                            {
                                WordDoc.Content.Tables[3].Cell(k, c).Range.Text = GetChineseNum(str);
                            }
                            else
                            {
                                int x = Convert.ToInt32(str);
                                int y = Convert.ToInt32(BlockColumn2);
                                WordDoc.Content.Tables[3].Cell(k, c).Range.Text = Convert.ToString(x + y);
                            }
                        }
                    }
                }


                /***********************往表里添加数据*******************************/
                int pRow2 = 2, qColumn2 = 1;
                int intindex = 0;
                int ids      = 0; //水分值的下标
                int ids2     = 0; //废纸包值的下标
                if (ds.Tables[0].Rows.Count > 0 || ds1.Tables[0].Rows.Count > 0)
                {
                    while (pRow2 <= WordDoc.Content.Tables[3].Rows.Count)//如果当前行pRow2小于表格的总行数
                    {
                        string str = WordDoc.Content.Tables[3].Cell(pRow2, qColumn2).Range.Text.Substring(0, WordDoc.Content.Tables[3].Cell(pRow2, qColumn2).Range.Text.Length - 2);

                        if (str == "")//如果为空单元格填写水分值
                        {
                            if (ids < ds.Tables[0].Rows.Count)
                            {
                                if (ds.Tables[0].Rows[ids][0] != null)
                                {
                                    WordDoc.Content.Tables[3].Cell(pRow2, qColumn2).Range.Text = ds.Tables[0].Rows[ids][0].ToString();
                                    ids++;
                                }
                            }
                        }
                        else
                        {                                                             //如果不为空单元格填写废纸包重量
                            if (ids2 < ds1.Tables[0].Rows.Count && str.Contains("扎")) //如果当前行数小于废纸包行数,单元格中包含“扎”字
                            {
                                if (ds1.Tables[0].Rows[ids2][0] != null)
                                {
                                    // intindex++;
                                    string strbox = "第" + ds1.Tables[0].Rows[ids2]["QCRecord_DRAW"].ToString() + "扎," + ds1.Tables[0].Rows[ids2]["QCRecord_RESULT"].ToString() + "KG".Trim();
                                    WordDoc.Content.Tables[3].Cell(pRow2, qColumn2).Range.Text = strbox;
                                    ids2++;
                                }
                            }
                        }

                        qColumn2++;
                        if (qColumn2 % WordDoc.Content.Tables[3].Columns.Count == 1)
                        {
                            pRow2++;
                            qColumn2 = 1;
                        }
                    }
                }
                #endregion
            }
            #endregion

            #region  测

            //strsql = sqlString.ElementAt(3);
            //ds = new DataSet();
            //ds = LinQBaseDao.Query(strsql);
            //if (ds != null && ds.Tables[0].Rows.Count > 0)
            //{

            //    int RowNum = ds.Tables[0].Rows.Count;
            //    int ColumnNum = WordDoc.Content.Tables[6].Columns.Count;

            //    //读模板
            //    int r = 0;         //从第几行计算BlockColumn和IDColumn;
            //    for (int i = 1; i <= WordDoc.Content.Tables[6].Rows.Count; i++)
            //    {

            //        for (int j = 1; j <= WordDoc.Content.Tables[6].Rows[i].Cells.Count; j++)
            //        {

            //            if (WordDoc.Content.Tables[6].Cell(i, j).Range.Text.Substring(0, WordDoc.Content.Tables[6].Cell(i, j).Range.Text.Length - 2) == "")
            //            {
            //                r = i;
            //                break;
            //            }
            //        }
            //        if (r != 0)
            //            break;
            //    }

            //    int IDColumn = 0, BlockColumn = 0;   //一行可以显示BlockColumn个数据
            //    for (int i = 1; i <= WordDoc.Content.Tables[6].Columns.Count; i++)
            //    {
            //        if (WordDoc.Content.Tables[6].Cell(r, i).Range.Text.Substring(0, WordDoc.Content.Tables[6].Cell(r, i).Range.Text.Length - 2) != "")
            //            IDColumn++;
            //        else
            //            BlockColumn++;
            //    }

            //    if (RowNum % BlockColumn != 0)
            //    {
            //        RowNum = RowNum / BlockColumn + 1;
            //    }
            //    else
            //    {
            //        RowNum = RowNum / BlockColumn;
            //    }

            //    for (int k = WordDoc.Content.Tables[6].Rows.Count + 1; k <= RowNum; k++)            //添加RowNum-1行
            //    {
            //        WordDoc.Content.Tables[6].Rows.Add(ref oMissing);
            //        for (int c = 1; c <= WordDoc.Content.Tables[6].Columns.Count; c++)            //初始化新添加行
            //        {
            //            string str = WordDoc.Content.Tables[6].Cell(k - 1, c).Range.Text.Substring(0, WordDoc.Content.Tables[6].Cell(k - 1, c).Range.Text.Length - 2);      //获取表格原来的值
            //            if (str == "")
            //            {
            //                WordDoc.Content.Tables[6].Cell(k, c).Range.Text = str;
            //            }
            //            else
            //            {
            //                int x = Convert.ToInt32(str);
            //                int y = Convert.ToInt32(IDColumn);
            //                WordDoc.Content.Tables[6].Cell(k, c).Range.Text = Convert.ToString(x + y);
            //            }
            //        }

            //    }

            //}
            //if (strsql != "")
            //{
            //    FindReplace(WordDoc, "{" + strsql + "}", "", 0);

            //}
            #endregion
            #endregion

            #region 打印预览
            WordApp.Visible = true;
            WordDoc.PrintPreview();//打印预览
            WordDoc.ReadingLayoutSizeX = 1024;
            WordDoc.ReadingLayoutSizeY = 756;
            #endregion


            #region 打印设置
            ////打印设置
            //try
            //{
            //    int dialogResult = WordApp.Dialogs[Microsoft.Office.Interop.Word.WdWordDialog.wdDialogFilePrint].Show(ref oMissing);
            //    if (dialogResult == 1)
            //    {
            //        //打印
            //        WordDoc.PrintOut(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,
            //              ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            //    }
            //    while (WordApp.BackgroundPrintingStatus > 0)
            //    {
            //        System.Threading.Thread.Sleep(250);
            //    }
            //}
            //catch (Exception ex)
            //{

            //    //Common.WriteTextLog("打印 GetPrint()" + ex.Message.ToString());
            //}
            //finally
            //{
            //    //消除Word 进程
            //    object SaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;

            //    WordDoc.Close(ref SaveChanges, ref oMissing, ref oMissing);
            //    if (WordApp != null)
            //        System.Runtime.InteropServices.Marshal.ReleaseComObject(WordDoc);
            //    WordDoc = null;


            //    WordApp.Quit(ref SaveChanges, ref oMissing, ref oMissing);
            //    GC.Collect();

            //}

            //object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatRTF;
            //object Target = System.Windows.Forms.Application.StartupPath + "//temp.rtf";
            //// 转换格式
            //oDoc.SaveAs(ref Target, 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

            //    OnClose(WordApp);
            //    MessageBox.Show("报表已生成!");

            //}
            //else
            //{
            //    return;
            //}
        }
        ////////////////////////////////////////
            //        MS-Word Processing
            ////////////////////////////////////////

            //Word.ApplicationClass wordApp = new Word.ApplicationClass();

        private void Func1()
        {
            Microsoft.Office.Interop.Word.ApplicationClass oWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document();

            object fileName = (object)@"D:\Documents and Settings\Haim\Desktop\Kan-Naim\test.doc";
            //object fileName = (object)@"D:\Documents and Settings\Haim\Desktop\Kan-Naim\ArticleEditor.doc";
            object oMissing = System.Reflection.Missing.Value;

            oWordApp.Visible = true;
            oWordDoc = oWordApp.Documents.Open(ref fileName, 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, ref oMissing);

            oWordDoc.ActiveWindow.Selection.WholeStory();
            oWordDoc.ActiveWindow.Selection.Copy();

            IDataObject data = Clipboard.GetDataObject();

            if (data != null) richTextBox1.Text = data.GetData(DataFormats.Text).ToString();

            object oTrue = true;
            object oFalse = false;

            Object oTemplatePath = (object)@"D:\Documents and Settings\Haim\Desktop\Kan-Naim\ArticleTemplate.dotx";
            oWordDoc = oWordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oTrue);

            Microsoft.Office.Tools.Word.RichTextContentControl richTextContentControl1;
            Microsoft.Office.Tools.Word.Document oWordTools = new Microsoft.Office.Tools.Word.Document();
            //oWordTools.Application.ActiveDocument.ContentControls = oWordApp;
            oWordTools.Paragraphs[1].Range.InsertParagraphBefore();
            oWordTools.Paragraphs[1].Range.Select();
            richTextContentControl1 = oWordTools.Controls.AddRichTextContentControl("richTextControl1");
            richTextContentControl1.PlaceholderText = "Enter your first name";

            //oWordDoc.ContentControls.get_Item(

        }
    protected void Button2_Click(object sender, EventArgs e)
    {
        SQLtoWord SW = new SQLtoWord();
        Button2.Enabled = false;

 string str = "SELECT mt.[year], mt.Depart, mt.[time], mt.teacher_Name, mt.specify, mt.guiNum, mt.IsOne,mt.IsTaskGive, mt.IsrefRead, mt.IsGuided, mt.totalsituation, ms.student_Name, ms.title, ms.kind AS kind, ms.Ischanged, ms.IsReq, ms.IsCom, ms.Attitude, ms.quality, ms.result, mt.QA FROM midCheckForTea mt CROSS JOIN midCheckForStu ms where mt.teacher_ID='" + Session["username"] + "' and mt.year='" + Session["year"] + "'and ms.student_ID='" + Session["student_ID"] + "'";
        DB db = new DB();
        DataSet ds = db.Select(str, db.DBconn());
        try
        {
            string tex = ds.Tables[0].Rows[0][1].ToString();
            string path1 = Server.MapPath(@"..\\过程文档\\文档模版\\中期检查.doc");
            string path2 = Server.MapPath("..\\过程文档\\中期检查") + "\\" + Session["student_ID"] +this.Label6.Text + "中期检查表.doc";
            if (ds.Tables[0].Rows[0]["kind"].Equals("理论研究"))
            {
                ds.Tables[0].Rows[0]["kind"] = "√理论研究    □应用研究    □技术开发    □其他( )";
            }
            else if (ds.Tables[0].Rows[0]["kind"].Equals("应用研究"))
            {
                ds.Tables[0].Rows[0]["kind"] = "□理论研究    √应用研究    □技术开发    □其他( )";
            }
            else if (ds.Tables[0].Rows[0]["kind"].Equals("技术开发"))
            {
                ds.Tables[0].Rows[0]["kind"] = "□理论研究    □应用研究    √技术开发    □其他( )";
            }
            else
            {
                ds.Tables[0].Rows[0]["kind"] = "□理论研究    □应用研究    □技术开发    √其他(" + ds.Tables[0].Rows[0]["kind"] + ")";
            }



            Microsoft.Office.Interop.Word.Application appWord = null;
            Microsoft.Office.Interop.Word.Document doc = null;
            try
            {
                appWord = new Microsoft.Office.Interop.Word.ApplicationClass();
                appWord.Visible = false;
                object objTrue = true;
                object objFalse = false;
                object objTemplate = path1;//模板路径
                object objDocType = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument;
                doc = appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);
                //第一步生成word文档
                //定义书签变量
                object[] obDD = new object[36];
                obDD[0] = "year";
                obDD[1] = "Depart";
                obDD[2] = "time";
                obDD[3] = "teacher_Name";
                obDD[4] = "specify";
                obDD[5] = "guiNum";
                obDD[6] = "IsOne";
                obDD[7] = "IsTaskGive";
                obDD[8] = "IsrefRead";
                obDD[9] = "IsGuided";
                obDD[10] = "totalsituation";
                obDD[11] = "student_Name1";
                obDD[12] = "student_Name2";
                obDD[13] = "title";
                obDD[14] = "kind1";
                obDD[15] = "kind2";
                obDD[16] = "kind3";
                obDD[17] = "Ischanged";
                obDD[18] = "IsReq";
                obDD[19] = "IsCom1";
                obDD[20] = "IsCom2";
                obDD[21] = "IsCom3";
                obDD[22] = "IsCom4";
                obDD[23] = "Attitude1";
                obDD[24] = "Attitude2";
                obDD[25] = "Attitude3";
                obDD[26] = "Attitude4";
                obDD[27] = "quality1";
                obDD[28] = "quality2";
                obDD[29] = "quality3";
                obDD[30] = "quality4";
                obDD[31] = "result1";
                obDD[32] = "result2";
                obDD[33] = "result3";
                obDD[34] = "result4";
                obDD[35] = "QA";
                for (int i = 0; i < 12; i++)
                {

                    doc.Bookmarks.get_Item(ref obDD[i]).Range.Text = ds.Tables[0].Rows[0][i].ToString(); 

                }
                doc.Bookmarks.get_Item(ref obDD[12]).Range.Text = ds.Tables[0].Rows[0][11].ToString();
                doc.Bookmarks.get_Item(ref obDD[13]).Range.Text = ds.Tables[0].Rows[0][12].ToString();
                //前13个循环加入书签,第13个开始要进行字符处理
                //14个是kind
                string str1 = ds.Tables[0].Rows[0][13].ToString();
                string[] sArray = str1.Split('√');

                doc.Bookmarks.get_Item(ref obDD[14]).Range.Text = sArray[0]; //加入书签

                doc.Bookmarks.get_Item(ref obDD[15]).Range.Text = ""; //加入书签

                doc.Bookmarks.get_Item(ref obDD[16]).Range.Text = sArray[1]; //加入书签

                // 15,16,个是 ms.Ischanged,ms.IsReq
                doc.Bookmarks.get_Item(ref obDD[17]).Range.Text = ds.Tables[0].Rows[0][14].ToString();
                doc.Bookmarks.get_Item(ref obDD[18]).Range.Text = ds.Tables[0].Rows[0][15].ToString();
                //17个是 ms.IsCom
                if (ds.Tables[0].Rows[0][16].Equals("提前完成"))
                {
                    doc.Bookmarks.get_Item(ref obDD[19]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[20]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[21]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[22]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][16].Equals("按计划完成"))
                {
                    doc.Bookmarks.get_Item(ref obDD[20]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[19]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[21]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[22]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][16].Equals("延期完成"))
                {
                    doc.Bookmarks.get_Item(ref obDD[21]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[19]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[20]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[22]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][16].Equals("没有完成"))
                {
                    doc.Bookmarks.get_Item(ref obDD[22]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[19]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[21]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[20]).Range.Text = "  ";
                }

                //18个是ms.Attitude
                if (ds.Tables[0].Rows[0][17].Equals("认真"))
                {
                    doc.Bookmarks.get_Item(ref obDD[23]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[24]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[25]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[26]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][17].Equals("较认真"))
                {
                    doc.Bookmarks.get_Item(ref obDD[24]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[23]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[25]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[26]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][17].Equals("一般"))
                {
                    doc.Bookmarks.get_Item(ref obDD[25]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[24]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[23]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[26]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][17].Equals("不认真"))
                {
                    doc.Bookmarks.get_Item(ref obDD[26]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[24]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[25]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[23]).Range.Text = "  ";
                }

                //19个是ms.result
                if (ds.Tables[0].Rows[0][18].Equals("优"))
                {
                    doc.Bookmarks.get_Item(ref obDD[27]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[28]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[29]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[30]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][18].Equals("良"))
                {
                    doc.Bookmarks.get_Item(ref obDD[28]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[27]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[29]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[30]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][18].Equals("中"))
                {
                    doc.Bookmarks.get_Item(ref obDD[29]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[28]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[27]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[30]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][18].Equals("差"))
                {
                    doc.Bookmarks.get_Item(ref obDD[30]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[28]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[29]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[27]).Range.Text = "  ";
                }

                //20个是ms.result
                if (ds.Tables[0].Rows[0][19].Equals("表扬"))
                {
                    doc.Bookmarks.get_Item(ref obDD[31]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[32]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[33]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[34]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][19].Equals("通过"))
                {
                    doc.Bookmarks.get_Item(ref obDD[32]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[31]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[33]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[34]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][19].Equals("警告"))
                {
                    doc.Bookmarks.get_Item(ref obDD[33]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[32]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[31]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[34]).Range.Text = "  ";
                }
                else if (ds.Tables[0].Rows[0][19].Equals("严重警告"))
                {
                    doc.Bookmarks.get_Item(ref obDD[34]).Range.Text = "√";
                    doc.Bookmarks.get_Item(ref obDD[32]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[33]).Range.Text = "  ";
                    doc.Bookmarks.get_Item(ref obDD[31]).Range.Text = "  ";
                }
                //21个是mt.QA

                doc.Bookmarks.get_Item(ref obDD[35]).Range.Text = ds.Tables[0].Rows[0][20].ToString();


                //第四步 生成word
                object filename = path2;
                object miss = System.Reflection.Missing.Value;
                try
                {
                    doc.SaveAs(ref filename, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                    //doc.Visible = true;//测试

                }
                catch
                {
                    // System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: " + DATAWORDPATH + tempFileName + WORDPOSTFIX);
                    Response.Write("<script>alert('系统找不到指定目录文件输出路径')<script>");
                }
                object missingValue = Type.Missing;
                object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
                doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);//关闭WordDoc文档对象 
                //关闭WordApp组件对象 

                appWord.Application.Quit(ref miss, ref miss, ref miss);
                doc = null;
                appWord = null;
                // Response.Write("<script>alert('文档写入成功!')<script>");
                //yi流的方式传送给客户端
                String filepath = path2;
                System.IO.FileInfo file = new System.IO.FileInfo(filepath);
                Response.Clear();
                Response.Charset = "GB2312";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                // 添加头信息,为"文件下载/另存为"对话框指定默认文件名 
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
                // 添加头信息,指定文件大小,让浏览器能够显示下载进度 
                Response.AddHeader("Content-Length", file.Length.ToString());

                // 指定返回的是一个不能被客户端读取的流,必须被下载 
                Response.ContentType = "application/ms-excel";

                // 把文件流发送到客户端 
                Response.WriteFile(file.FullName);
                // 停止页面的执行 
                Response.End();

            }
            catch (System.Exception a)
            {
                //捕捉异常,如果出现异常则清空实例,退出word,同时释放资源
                string aa = a.ToString();
                object miss = System.Reflection.Missing.Value;
                object missingValue = Type.Missing;
                object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
                doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
                appWord.Application.Quit(ref miss, ref miss, ref miss);
                doc = null;
                appWord = null;
                Response.Write("<script>alert('向word文件中写入数据出错。');location='midCheckEA.aspx'</script>");
               
                return;
            }
        }
        catch
        {
            Response.Write("<script>alert('数据库出错,您可能还未提交中期检查表.');location='midCheckEA.aspx'</script>");
            return;
        }
        finally
        {

            ds.Clear();
            Button2.Enabled = true;
        }

    }
示例#49
0
 //将listview中的数据导出到word中
 private void DoWord(ListView listView, string strFileName)
 {
     int rowNum = listView.Items.Count;//表格的行数
     int columnNum = listView.Items[0].SubItems.Count;//表格的列数
     int rowIndex = 1;
     int columnIndex = 0;
     if (rowNum == 0 || string.IsNullOrEmpty(strFileName))
     {
         return;
     }
     if (rowNum > 0)
     {
         object oMissing = System.Reflection.Missing.Value;
         Microsoft.Office.Interop.Word.Application WordApp;
         Microsoft.Office.Interop.Word.Document WordDoc;
         WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
         WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
         WordApp.ActiveDocument.PageSetup.PageWidth = WordApp.CentimetersToPoints(float.Parse("29.71"));//纸张宽度(A3)
         WordApp.ActiveDocument.PageSetup.PageHeight = WordApp.CentimetersToPoints( float.Parse( "42.01" ) );//纸张高度(A3)
         string strContent = "员工日志\n ";//标题
         WordDoc.Paragraphs.First.Range.Text = strContent;
         WordDoc.Paragraphs.First.Range.Font.Size = 18;//设置标题字体大小
         WordDoc.Paragraphs.First.Range.Font.Bold = 2;//设置标题加粗
         WordDoc.Paragraphs.First.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//设置标题为居中
         //WordApp.Selection.TypeParagraph();//插入段落
         Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Paragraphs.Last.Range;//插入表格的位置
         Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(tableLocation, rowNum+1, columnNum, ref oMissing, ref oMissing);//插入表格
         newTable.Borders.Enable = 1;
         newTable.Select();//选中表格
         WordApp.Selection.Tables[1].Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter;//表格居中
         //表格的第一行存listview各列的列名
         foreach (ColumnHeader dc in listView.Columns)
         {
             columnIndex++;
             newTable.Cell(rowIndex, columnIndex).Range.Text = dc.Text;
             newTable.Cell(rowIndex, columnIndex).Range.Bold = 2;//设置单元格中表头字体为粗体
             //设置表头字体居中
             newTable.Cell(rowIndex, columnIndex).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
         }
         newTable.Columns[1].Width = 40f;//设置第一列"序号"的宽度
         //将listview中的日志保存到表格中,从表格的第二行开始存
         for (int i =0; i < rowNum; i++)
         {
             rowIndex = 2;
             columnIndex = 0;
             for (int j = 0; j < columnNum; j++)
             {
                 columnIndex++;
                 newTable.Cell(rowIndex, columnIndex).Range.Text = Convert.ToString(listView.Items[i].SubItems[j].Text) + "\t";
             }
         }
             WordDoc.SaveAs(strFileName, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
         //关闭WordDoc文档对象
         WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
         MessageBox.Show("日志导出成功");
         //关闭WordApp组件对象
         WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
     }
 }