Excel中自定义属性

public static string GetCustomProperty(this Excel.Workbook book, string propertyName)

        {

            //string strResult = string.Empty;

            //Office.DocumentProperties pros = (Office.DocumentProperties)book.CustomDocumentProperties;

            //strResult = GetCustomProperty(pros, propertyName);

            //if (!string.IsNullOrEmpty(strResult))

            //{

            //    return strResult;

            //}

            //int index = 1;

            //while (true)

            //{

            //    string pName = propertyName + index++.ToString();

            //    string pValue = GetCustomProperty(pros, pName);

            //    if (string.IsNullOrEmpty(pValue))

            //    {

            //        break;

            //    }

            //    else

            //    {

            //        strResult += pValue;

            //    }

            //}

            //return strResult;

            string strResult = string.Empty;



            var bookType = book.GetType();

            var pros = bookType.InvokeMember("CustomDocumentProperties", System.Reflection.BindingFlags.GetProperty, null, book, null);

            var propertiesType = pros.GetType();



            var enumerator = (IEnumerator)propertiesType.InvokeMember("GetEnumerator", System.Reflection.BindingFlags.InvokeMethod, null, pros, null);

            Func<string, string> getPropertyValue = new Func<string, string>(s =>

            {

                string strValue = string.Empty;

                enumerator.Reset();

                while (enumerator.MoveNext())

                {

                    var p = enumerator.Current;

                    var name = p.GetType().InvokeMember("Name", System.Reflection.BindingFlags.GetProperty, null, p, null);

                    if (name != null && name.ToString().Equals(propertyName))

                    {

                        return (string)p.GetType().InvokeMember("Value", System.Reflection.BindingFlags.GetProperty, null, p, null);

                    }

                }

                return strValue;

            });



            strResult = getPropertyValue(propertyName);

            if (!string.IsNullOrEmpty(strResult))

            {

                return strResult;

            }

            int index = 1;

            while (true)

            {

                string pName = propertyName + index++.ToString();

                string pValue = getPropertyValue(pName);

                if (string.IsNullOrEmpty(pValue))

                {

                    break;

                }

                else

                {

                    strResult += pValue;

                }

            }

            return strResult;

        }


注掉的代码,在多线程操作中会出错

 

你可能感兴趣的:(Excel)