Ejemplo n.º 1
0
    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>");
        }
    }
Ejemplo n.º 2
0
    protected object isVisible = false; //The process has to be in invisible mode

    // implementing the method of the 'IDocumentReader' interface
    /// <summary>
    /// Read the document's content
    /// </summary>
    /// <param name="path">Path of the file to be read</param>
    /// <param name="alertMessage">Message to be alerted on document import (usually to indicate an error)</param>
    /// <returns>HTML content of the document to be imported</returns>
    public string GetHtml(string path, out string alertMessage)
    {
        alertMessage = "";                                                        // no alert by default
        string result = "";                                                       // result content

        Microsoft.Office.Interop.Word.ApplicationClass objApp = null;             // MS Word application
        object hName = path + ".html";                                            // temporary HTML file
        object wName = path;                                                      // path of the source file
        string url   = System.Web.HttpContext.Current.Request.QueryString["url"]; // relative URL of the source file

        // comment the following line if you want to have relative URL's in the document
        url = Obout.Ajax.UI.HTMLEditor.Popups.GalleryManager.GetHttpRoot(System.Web.HttpContext.Current.Request) + url;

        string clearedFileName = HttpUtility.UrlPathEncode(Path.GetFileName(path)); // cleared file name of the source

        if (File.Exists(hName.ToString()))                                          // remove the temporary file if exists
        {
            if (CanAccess(hName.ToString()))
            {
                File.Delete(hName.ToString());
            }
        }

        try
        {
            // create application
            objApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            // open document
            objApp.Documents.Open(ref wName, ref missing, ref readOnly, 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);
            // make the application invisible
            objApp.Visible = false;
            // get the active document
            Microsoft.Office.Interop.Word.Document oDoc = objApp.ActiveDocument;
            // save it to the temporay HTML file
            oDoc.SaveAs(ref hName, ref fltDocFormat, 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);
            // quite the application
            objApp.Quit(ref missing, ref missing, ref missing);

            // get the content of the temporary HTML file
            if (CanAccess(hName.ToString()))
            {
                // get styles and body's content from the temporary HTML document
                result = (new Obout.Ajax.UI.HTMLEditor.Popups.HtmlReader()).GetHtml(hName.ToString(), out alertMessage);
                // for images URL's
                result = result.Replace(clearedFileName, url);
                // we don't need this file anymore
                File.Delete(hName.ToString());
            }
        }
        catch (Exception ex)
        {
            // something wrong...
            alertMessage = ex.Message;
        }
        finally
        {
            // ensure the MS Word application is stopped
            if (objApp != null)
            {
                objApp = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        return(result);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int   count  = 0;
            int   ocount = 0;
            float per    = 0;
            float max    = 0;
            con = new SqlConnection(ConfigurationManager.AppSettings["LIS"]);
            cmd = new SqlCommand();
            con.Open();
            cmd.Connection  = con;
            cmd.CommandText = "select pname from Papers";
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                //Read file from location
                string pname = dr.GetString(0).ToString();


                //reader.Close();
                //TextBox1.Text = TextBox1.Text + " " + textPdf.ToString();


                //word File Code
                //   string file =pname;
                StringBuilder textWord = new StringBuilder();
                Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                object miss     = System.Reflection.Missing.Value;
                object path     = @Server.MapPath("~/Admin/Paper/" + pname);
                object readOnly = true;
                Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, 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);

                for (int i = 0; i < docs.Paragraphs.Count; i++)
                {
                    textWord.Append(" \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString());
                }
                //TextBox1.Text = text.ToString();
                // text.Append(textWord.ToString());

                docs.Close();



                //Compare file

                string       newfile  = "~/Paper/AllPaper.txt";//path to text file
                StreamReader testTxt1 = new StreamReader(Server.MapPath(newfile));
                string       text1    = testTxt1.ReadToEnd();
                // Split the text block into an array of sentences.

                string[] sentences1 = text1.Split(new char[] { '.', '?', '!', ',' });
                // Response.Write(sentences1[1]);
                for (int i = 0; i < sentences1.Length; i++)
                {
                    // string oldfile = textPdf.ToString();//path to text file
                    // StreamReader testTxt = new StreamReader(Server.MapPath(oldfile));
                    string text = textWord.ToString();
                    // Split the text block into an array of sentences.

                    string[] sentences = text.Split(new char[] { '.', '?', '!' });
                    ocount = sentences.Length;
                    // Define the search terms. This list could also be dynamically populated at runtime.


                    string[] wordsToMatch;
                    wordsToMatch    = new string[1];
                    wordsToMatch[0] = sentences1[i];
                    // Find sentences that contain all the terms in the wordsToMatch array.
                    // Note that the number of terms to match is not specified at compile time.
                    var sentenceQuery = from sentence in sentences
                                        let w = sentence.Split(new char[] { '.', '?', '!', ';', ':', ',' },

                                                               StringSplitOptions.RemoveEmptyEntries)

                                                where w.Distinct().Intersect(wordsToMatch).Count() == wordsToMatch.Count()

                                                select sentence;
                    foreach (string str in sentenceQuery)
                    {
                        //  Response.Write("Hloo");
                        // Response.Write(str + ".");
                        //  txtFirstItem.Text = txtFirstItem.Text + " " + str + ".";
                        count++;
                        break;
                    }
                    //    Response.Write("Hloo");
                    // testTxt.Close();
                }
                //end for loop


                per = (count * 100) / ocount;
                if (per > max)
                {
                    max = per;
                }
            }
            //  float val = count / ocount;

            if (max > 100)
            {
                lblCount.Text = "100";
            }
            else
            {
                lblCount.Text = max.ToString();
            }

            if (max < 20)
            {
                lblStatus.Text = "Accepted";
            }
            else
            {
                lblStatus.Text = "Rejected";
            }
        }
    }