如何从特定的Word或Excel文档中获取设计属性值?

时间:2012-10-21 06:40:15

标签: c# office-interop

是否可以从特定文档中获取设计属性值?如果是这样,我将使用什么方法,以及如何使用?

示例:

我有file.docx,然后file.docx有一个字体为Tahoma的文本,大小为74,样式为粗体和斜体。现在,我想获取属性的值到设置字体的位置,大小和样式(注意:值,而不是属性)。如果这是可能的,它也适用于样式表等吗?

1 个答案:

答案 0 :(得分:0)

对于Word文档:

using Microsoft.Office.Interop.Word;

        namespace ConsoleApplication1
        {
            class Program
            {
                static void Main(string[] args)
                {

                    Application application = new Application();
                    application.Visible = false;


                    Document document = application.Documents.Open(@"C:\file.docx", Type.Missing, true);

                    // Loop through all words in the document.
                    int count = document.Words.Count;
                    for (int i = 1; i <= count; i++)
                    {
                        string text = document.Words[i].Text; //you can validate if string.IsNullOrEmpty....
                        string fontName = document.Words[i].Font.Name;
                        string bold = document.Words[i].Font.Bold.ToString();
                        string fontSize = document.Words[i].Font.Size.ToString();
                        Console.WriteLine("Word {0} = {1} -- Font:{2}, Size: {3}, Bold:{4}", i, text, fontName, fontSize, bold);
                    }


                    application.Quit();

                    Console.ReadLine();

                   }
            }
        }

Excel Document:

using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

...

     static void Main(string[] args)
            {

                Application application = new Application();
                application.Visible = false;
                string filePath = @"C:\excel.xlsx";

                var book = application.Workbooks.Open(filePath, Type.Missing, true);

                Workbook workBook = application.Workbooks.Open(filePath,
                                                                Type.Missing, true, Type.Missing, Type.Missing,
                                                                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                                Type.Missing, Type.Missing);



                foreach (Worksheet item in workBook.Sheets)
                {
                    foreach (Range cell in item.Cells)
                    {
                        //Navigate huge options... 
                        //.Borders
                        //.Style
                        //... 
                    }

                }



                workBook.Close(false, filePath, null);
                Marshal.ReleaseComObject(workBook);

                application.Quit();

                Console.ReadLine();


            }