如何识别Excel自定义属性是否存在
本文关键字:Excel 自定义属性 是否 存在 识别 何识别 | 更新日期: 2023-09-27 18:02:47
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);
}
}
string [] files = System.IO.Directory.GetFiles(directory);
如果你像这样把excel文件放在你的项目中,你可以使用server mappathstring[] files = System.IO.Directory.GetFiles(Server.MapPath("~'upload"));
这一行会给你一个目录中已经存在的所有文件,这样你就可以检查文件是否已经存在而不会得到一个异常