如何识别Excel自定义属性是否存在?

时间:2015-07-14 09:55:28

标签: c#

using Excel = Microsoft.Office.Interop.Excel;

我正在使用一种方法来设置Excel自定义属性,但是如果该属性已经存在则抛出异常,以及如果属性已经存在我将如何更新该属性

public Excel.Workbook workBk;
Application _excelApp;

public void SetDocumentProperty(string propertyName, string propertyValue)
{
    try
    {
        _excelApp = new Application();
        workBk = _excelApp.Workbooks.Open(@"C:\12345.xlsx",
        Type.Missing, Type.Missing, Type.Missing, Type.Missing,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing,
        Type.Missing, Type.Missing);

        object oDocCustomProps = workBk.CustomDocumentProperties;
        Type typeDocCustomProps = oDocCustomProps.GetType();

         object[] oArgs = {propertyName,false,
         MsoDocProperties.msoPropertyTypeString,
         propertyValue};

         typeDocCustomProps.InvokeMember("Add", BindingFlags.Default |
                                       BindingFlags.InvokeMethod, null,
                                       oDocCustomProps, oArgs);
         workBk.Save();
    }
    finally
    {
         workBk.Close(false, @"C:\12345.xlsx", null);
         Marshal.ReleaseComObject(workBk);
    }
}

1 个答案:

答案 0 :(得分:0)

        string [] files = System.IO.Directory.GetFiles(directory);

如果你把excel文件放在你的项目中,你可以使用服务器mappath   string [] files = System.IO.Directory.GetFiles(Server.MapPath(“〜\ upload”));

这一行将为你提供目录中已经存在的所有文件,你可以检查文件是否已经存在而不会出现异常

相关问题