Esempio n. 1
0
        /// <summary>
        /// 设置文档格式并添加内容
        /// </summary>
        /// <param name="filePath">文件名</param>
        /// <returns></returns>
        public static bool AddContent(string filePath)
        {
            try
            {
                Object oMissing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word._Application WordApp = new Application();
                WordApp.Visible = true;
                object filename = filePath;
                Microsoft.Office.Interop.Word._Document 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);

                //设置居左
                WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;

                //设置文档的行间距
                WordApp.Selection.ParagraphFormat.LineSpacing = 15f;
                //插入段落
                //WordApp.Selection.TypeParagraph();
                Microsoft.Office.Interop.Word.Paragraph para;
                para = WordDoc.Content.Paragraphs.Add(ref oMissing);
                //正常格式
                para.Range.Text = "This is paragraph 1";
                //para.Range.Font.Bold = 2;
                //para.Range.Font.Color = WdColor.wdColorRed;
                //para.Range.Font.Italic = 2;
                para.Range.InsertParagraphAfter();

                para.Range.Text = "This is paragraph 2";
                para.Range.InsertParagraphAfter();

                //插入Hyperlink
                Microsoft.Office.Interop.Word.Selection mySelection = WordApp.ActiveWindow.Selection;
                mySelection.Start = 9999;
                mySelection.End   = 9999;
                Microsoft.Office.Interop.Word.Range myRange = mySelection.Range;

                Microsoft.Office.Interop.Word.Hyperlinks myLinks = WordDoc.Hyperlinks;
                object linkAddr = @"http://www.cnblogs.com/lantionzy";
                Microsoft.Office.Interop.Word.Hyperlink myLink = myLinks.Add(myRange, ref linkAddr,
                                                                             ref oMissing);
                WordApp.ActiveWindow.Selection.InsertAfter("\n");

                //落款
                WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();
                WordDoc.Paragraphs.Last.Alignment  = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                //保存
                WordDoc.Save();
                WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(false);
            }
        }
        public void ValidateHyperlinks()
        {
            Word.Hyperlinks links       = this.Application.ActiveDocument.Hyperlinks;
            FailedLinks     failedLinks = new FailedLinks();

            foreach (var hyperlink in links)
            {
                var hp = (Word.Hyperlink)hyperlink;

                try
                {
                    WebRequest request = WebRequest.Create(new Uri(hp.Address));
                    request.Method = "HEAD";

                    using (WebResponse response = request.GetResponse())
                    {
                        if (response.ContentLength < 1)
                        {
                            failedLinks.Add(hp, "Link content is empty");
                        }
                    }
                }
                catch (WebException webEx)
                {
                    string message = webEx.InnerException is FileNotFoundException
                        ? "File not found"
                        : "Unable to resolve Hyperlink";

                    failedLinks.Add(hp, message);
                }
            }
        }
 static void Main(string[] args)
 {
     Microsoft.Office.Interop.Word.Hyperlinks links1 = readDoc(path + "EmployeeDocument.docx");
     ReadHyperLinks(links1);
     ((_Document)doc).Close();
     ((_Application)word).Quit();
     Console.Read();
 }
Esempio n. 4
0
 private static void CreateWordDocument(string Link, string FilePath = "")
 {
     try
     {
         Microsoft.Office.Interop.Word._Application MSWORD = new Microsoft.Office.Interop.Word.Application();
         MSWORD.Visible = false;
         object missing = Type.Missing;
         Microsoft.Office.Interop.Word._Document MSWORDdoc = MSWORD.Documents.Add(ref missing, ref missing, ref missing, ref missing);
         Microsoft.Office.Interop.Word.Paragraph TEXTBLOCK = MSWORDdoc.Paragraphs.Add(ref missing);
         object style_name = "Heading 1";
         TEXTBLOCK.Range.set_Style(ref style_name);
         TEXTBLOCK.Range.InsertParagraphAfter();
         if (string.IsNullOrEmpty(FilePath))
         {
             TEXTBLOCK.Range.Text = RandomString_Contents(randLength.Next(5, 999));
         }
         else
         {
             TEXTBLOCK.Range.Text = RandomString_Words(FilePath);
         }
         TEXTBLOCK.Range.InsertParagraphAfter();
         object filename  = Directory.GetCurrentDirectory() + "\\" + RandomString_Contents(randLength.Next(3, 12)) + ".doc";
         string PREV_FONT = TEXTBLOCK.Range.Font.Name;
         TEXTBLOCK.Range.Font.Name = "Courier New";
         TEXTBLOCK.Range.InsertParagraphAfter();
         TEXTBLOCK.Range.Font.Name = PREV_FONT;
         Microsoft.Office.Interop.Word.Hyperlinks myLinks = MSWORDdoc.Hyperlinks;
         if (Link.Contains("http") == false && Link.Contains("https") == false)
         {
             Link = "http://" + Link;
         }
         object linkAddr = Link;
         Microsoft.Office.Interop.Word.Selection mySelection = MSWORDdoc.ActiveWindow.Selection;
         mySelection.Start = 9999;
         mySelection.End   = 9999;
         Microsoft.Office.Interop.Word.Range     myRange = mySelection.Range;
         Microsoft.Office.Interop.Word.Hyperlink myLink  = myLinks.Add(myRange, ref linkAddr, ref missing);
         MSWORDdoc.ActiveWindow.Selection.InsertAfter("\n");
         MSWORDdoc.SaveAs(ref filename, 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);
         object save_changes = false;
         MSWORDdoc.Close(ref save_changes, ref missing, ref missing);
         MSWORD.Quit(ref save_changes, ref missing, ref missing);
         Console.WriteLine("App done! .Doc created!");
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
         Console.WriteLine(e.StackTrace);
     }
 }
        public static Hyperlinks readDoc(string file)
        {
            object fileName = file;
            object missing  = System.Type.Missing;

            doc = word.Documents.Open(ref fileName, false, 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);
            String read = string.Empty;

            Microsoft.Office.Interop.Word.Hyperlinks links = doc.Hyperlinks;
            List <string> data = new List <string>();

            foreach (Paragraph objParagraph in doc.Paragraphs)
            {
                Console.WriteLine(objParagraph.Range.Text.Trim());
            }

            Console.Write("******************** End Of File *******************************\n");

            return(links);
        }
Esempio n. 6
0
        private void btn_LinkText_Click(object sender, RibbonControlEventArgs e)
        {
            Word.Hyperlinks myLinks = Globals.ThisAddIn.Application.ActiveDocument.Hyperlinks;
            string          anchor  = InputDialog.ShowDialog("What text do you want linked (case sensitive)?", "Link Text");

            if (!String.IsNullOrEmpty(anchor))
            {
                string link     = InputDialog.ShowDialog("Where do you want the link to point (leave blank to remove link)?", "Link Text");
                object findText = anchor;
                Globals.ThisAddIn.Application.Selection.Find.Execute(findText, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, Word.WdFindWrap.wdFindAsk, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                if (Globals.ThisAddIn.Application.Selection.Find.Found)
                {
                    while (Globals.ThisAddIn.Application.Selection.Find.Found)
                    {
                        if (String.IsNullOrEmpty(link))
                        {
                            if (Globals.ThisAddIn.Application.Selection.Hyperlinks.Count > 0)
                            {
                                DialogResult result = MessageBox.Show("You entered a blank link. Do you wish to remove existing links? Click Yes to continue. Click No to ignore this one instance. Click Cancel to abort the whole linking process.", "Link Text: Confirm Removal", MessageBoxButtons.YesNoCancel);
                                if (result == DialogResult.Yes)
                                {
                                    Debug.WriteLine("Removing link from the anchor '" + anchor + "'.");
                                    foreach (Word.Hyperlink objLink in Globals.ThisAddIn.Application.Selection.Hyperlinks)
                                    {
                                        objLink.Delete();
                                    }
                                }
                                else if (result == DialogResult.No)
                                {
                                    Debug.WriteLine("Skipping this instance of the anchor.");
                                }
                                else
                                {
                                    Debug.WriteLine("Aborting!");
                                    break;
                                }
                            }
                        }
                        else
                        {
                            if (Globals.ThisAddIn.Application.Selection.Hyperlinks.Count > 0)
                            {
                                DialogResult result = MessageBox.Show("This instance of the text is already linked. Do you want to update this link to '" + link + "'? Click Yes to proceed. Click No to skip this one instance. Click Cancel to abort the whole linking process.", "Link Text: Confirm Link", MessageBoxButtons.YesNoCancel);
                                if (result == DialogResult.Yes)
                                {
                                    Debug.WriteLine("Updating link to the anchor '" + anchor + "', pointing to '" + link + "'.");
                                    foreach (Word.Hyperlink objLink in Globals.ThisAddIn.Application.Selection.Hyperlinks)
                                    {
                                        objLink.Delete();
                                    }
                                    Word.Hyperlink mylink = myLinks.Add(Globals.ThisAddIn.Application.Selection.Range, link);
                                }
                                else if (result == DialogResult.No)
                                {
                                    Debug.WriteLine("Skipping this instance of the anchor.");
                                }
                                else
                                {
                                    Debug.WriteLine("Aborting!");
                                    break;
                                }
                            }
                            else
                            {
                                DialogResult result = MessageBox.Show("Do you wish to link the selected text? It will point to the following URL: '" + link + "'. Click Yes to proceed. Click No to skip this one instance. Click Cancel to abort the whole linking process.", "Link Text: Confirm Link", MessageBoxButtons.YesNoCancel);
                                if (result == DialogResult.Yes)
                                {
                                    Debug.WriteLine("Adding link to the anchor '" + anchor + "', pointing to '" + link + "'.");
                                    Word.Hyperlink mylink = myLinks.Add(Globals.ThisAddIn.Application.Selection.Range, link);
                                }
                                else if (result == DialogResult.No)
                                {
                                    Debug.WriteLine("Skipping this instance of the anchor.");
                                }
                                else
                                {
                                    Debug.WriteLine("Aborting!");
                                    break;
                                }
                            }
                        }
                        Globals.ThisAddIn.Application.Selection.Find.Execute(findText, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, Word.WdFindWrap.wdFindAsk, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                    }
                    MessageBox.Show("Linking process complete.");
                }
                else
                {
                    MessageBox.Show("No instances of '" + anchor + "' found. Remember that the search is case sensitive and, if text is selected, will only search inside that text.");
                }
            }
        }
Esempio n. 7
0
        /// <summary>
        /// 规范表格,而且删除表格中的嵌入式图片
        /// </summary>
        /// <param name="TableStyle">要应用的表格样式</param>
        /// <param name="ParagraphFormat">表格中的段落样式</param>
        /// <param name="blnDeleteShapes">是否要删除表格中的图片,包括嵌入式或非嵌入式图片。</param>
        /// <remarks></remarks>
        public void TableFormat(string TableStyle    = "zengfy表格-上下总分型1", string ParagraphFormat = "表格内容置顶",
                                bool blnDeleteShapes = false)
        {
            var Selection = _app.Selection;

            if (Selection.Tables.Count > 0)
            {
                //定位表格
                Table Tb = default(Table);
                Range rg = default(Range);
                foreach (Table tempLoopVar_Tb in Selection.Range.Tables)
                {
                    Tb   = tempLoopVar_Tb;
                    rg   = Tb.Range;
                    _app = Tb.Application;
                    //
                    _app.ScreenUpdating = false;

                    //调整表格尺寸
                    dynamic with_1 = Tb;
                    with_1.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitContent);
                    with_1.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitWindow);

                    //清除表格中的超链接
                    Hyperlinks hps = default(Hyperlinks);
                    hps = rg.Hyperlinks;

                    int hpCount = 0;
                    hpCount = hps.Count;
                    for (var i = 1; i <= hpCount; i++)
                    {
                        hps[1].Delete();
                    }

                    //将手动换行符删除
                    {
                        Tb.Range.Find.ClearFormatting();
                        Tb.Range.Find.Replacement.ClearFormatting();
                        Tb.Range.Find.Text             = "^l";
                        Tb.Range.Find.Replacement.Text = "";
                        Tb.Range.Find.Execute(WdReplace.wdReplaceAll);
                    }
                    //删除表格中的乱码空格
                    {
                        Tb.Range.Find.ClearFormatting();
                        Tb.Range.Find.Replacement.ClearFormatting();
                        Tb.Range.Find.Text             = " ";
                        Tb.Range.Find.Replacement.Text = " ";
                        Tb.Range.Find.Execute(WdReplace.wdReplaceAll);
                    }

                    //删除表格中的嵌入式图片
                    if (blnDeleteShapes)
                    {
                        InlineShapes inlineshps = default(InlineShapes);
                        int          Count      = 0;
                        InlineShape  inlineShp  = default(InlineShape);
                        inlineshps = Tb.Range.InlineShapes;
                        Count      = inlineshps.Count;
                        for (var i = Count; i >= 1; i--)
                        {
                            inlineShp = inlineshps[Convert.ToInt32(i)];
                            inlineShp.Delete();
                        }
                        //删除表格中的图片
                        ShapeRange shps = default(ShapeRange);
                        Shape      shp  = default(Shape);
                        shps  = Tb.Range.ShapeRange;
                        Count = shps.Count;
                        for (var i = Count; i >= 1; i--)
                        {
                            shp = shps[i];
                            shp.Delete();
                        }
                    }

                    //清除表格中的格式设置
                    rg.Select();
                    Selection.ClearFormatting();

                    // ----- 设置表格样式与表格中的段落样式
                    try //设置表格样式
                    {
                        Tb.set_Style(TableStyle);
                    }
                    catch (Exception)
                    {
                    }
                    try //设置表格中的段落样式
                    {
                        rg.ParagraphFormat.set_Style(ParagraphFormat);
                    }
                    catch (Exception)
                    {
                    }
                }

                //取消选择并刷新界面
                Selection.Collapse();
                _app.ScreenRefresh();
                _app.ScreenUpdating = true;
            }
            else
            {
                MessageBox.Show("请至少选择一个表格。", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            //get user's desktop path for log file, and add log file name
            string logFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\containsLink_log.txt";

            //retrive file names from user's specified directory and sub directories
            Console.WriteLine("Enter directory to search:  ");
            string path = Console.ReadLine();

            string[] myFiles = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);

            //process each file
            foreach (string filename in myFiles)
            {
                //skip file if just temp file
                if (filename.Substring(0, 1) != "~")
                {
                    //write filename to log file
                    System.IO.File.AppendAllText(logFilePath, filename);
                    System.IO.File.AppendAllText(logFilePath, Environment.NewLine);
                    Console.WriteLine(filename);

                    //make list to store file's links
                    List <string> links = new List <string>();

                    //find file's extension (type)
                    int    extLoc  = filename.LastIndexOf(".");
                    int    endLoc  = filename.Length - extLoc - 1;
                    string fileExt = filename.Substring(extLoc + 1, endLoc);

                    //process file according to its type, extracting the file's links
                    if (fileExt == "pdf")
                    {
                        //Setup some variables to be used later
                        PdfReader     reader         = default(PdfReader);
                        int           pageCount      = 0;
                        PdfDictionary pageDictionary = default(PdfDictionary);
                        PdfArray      annots         = default(PdfArray);

                        //Open our reader
                        reader = new PdfReader(filename);
                        //Get the page cont
                        pageCount = reader.NumberOfPages;

                        //Loop through each page
                        for (int i = 1; i <= pageCount; i++)
                        {
                            //Get the current page
                            pageDictionary = reader.GetPageN(i);
                            //Get all of the annotations for the current page
                            annots = pageDictionary.GetAsArray(PdfName.ANNOTS);
                            //Make sure we have something
                            if ((annots == null) || (annots.Length == 0))
                            {
                                Console.WriteLine("nothing");
                            }
                            //Loop through each annotation
                            if (annots != null)
                            {
                                //add page number to list
                                links.Add("Page " + i);

                                foreach (PdfObject A in annots.ArrayList)
                                {
                                    //Convert the itext-specific object as a generic PDF object
                                    PdfDictionary AnnotationDictionary =
                                        (PdfDictionary)PdfReader.GetPdfObject(A);
                                    //Make sure this annotation has a link
                                    if (!AnnotationDictionary.Get(PdfName.SUBTYPE).Equals(PdfName.LINK))
                                    {
                                        continue;
                                    }
                                    //Make sure this annotation has an ACTION
                                    if (AnnotationDictionary.Get(PdfName.A) == null)
                                    {
                                        continue;
                                    }
                                    //Get the ACTION for the current annotation
                                    PdfDictionary AnnotationAction =
                                        AnnotationDictionary.GetAsDict(PdfName.A);
                                    // Test if it is a URI action
                                    if (AnnotationAction.Get(PdfName.S).Equals(PdfName.URI))
                                    {
                                        PdfString Destination = AnnotationAction.GetAsString(PdfName.URI);
                                        string    url         = Destination.ToString();

                                        //add url to list
                                        links.Add(url);
                                    }
                                }
                            }
                        }
                    }
                    else if ((fileExt == "xls") || (fileExt == "xlsx"))
                    {
                        Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
                        excelApp.Visible = false;

                        //open excel file
                        Workbook excelWorkbook = excelApp.Workbooks.Open(filename, 0, true, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);
                        Sheets   excelSheets   = excelWorkbook.Worksheets;

                        //loop through worksheets
                        for (int i = 1; i <= excelSheets.Count; i++)
                        {
                            Worksheet sheet = (Worksheet)excelSheets.Item[i];

                            //extract links
                            if (sheet.Hyperlinks.Count > 0)
                            {
                                links.Add("Page " + i);

                                for (int j = 1; j <= sheet.Hyperlinks.Count; j++)
                                {
                                    string address = sheet.Hyperlinks[i].Address;
                                    links.Add(address);
                                }
                            }
                        }

                        excelWorkbook.Close(false);
                        excelApp.Quit();
                    }
                    else if ((fileExt == "doc") || (fileExt == "docx"))
                    {
                        Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                        Document doc = wordApp.Documents.Open(FileName: filename, ReadOnly: true);
                        Microsoft.Office.Interop.Word.Hyperlinks hyperlinks = doc.Hyperlinks;

                        if (hyperlinks.Count > 0)
                        {
                            //links.Add("Page: ");

                            foreach (var hyperlink in hyperlinks)
                            {
                                string address = ((Microsoft.Office.Interop.Word.Hyperlink)hyperlink).Address;
                                links.Add(address);
                            }
                        }

                        doc.Close(false);
                        wordApp.Quit(false);
                    }
                    else if ((fileExt == "csv") || (fileExt == "txt"))
                    {
                        string[] lines = System.IO.File.ReadAllLines(filename);

                        foreach (string line in lines)
                        {
                            foreach (Match item in Regex.Matches(line, @"(http(s)?://)?([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?"))
                            {
                                string address = item.Value;
                                links.Add(address);
                            }
                        }
                    }
                    else
                    {
                    }

                    //write the file's link count to the log file
                    //have to subtract the page number markers from the links count
                    int fileLinkCount = 0;
                    foreach (string line in links)
                    {
                        if (line.Substring(0, 4) != "Page")
                        {
                            fileLinkCount++;
                        }
                    }
                    System.IO.File.AppendAllText(logFilePath, "Link count: " + fileLinkCount + Environment.NewLine);

                    //write the file's links to the log file
                    if (links.Count > 0)
                    {
                        using (TextWriter tw = new StreamWriter(logFilePath, append: true))
                        {
                            foreach (String s in links)
                            {
                                tw.WriteLine(s);
                            }
                        }
                    }

                    System.IO.File.AppendAllText(logFilePath, "----------" + Environment.NewLine);
                }
            }
        }