首页 > 解决方案 > 如何使用 C# 将自定义属性添加到 Excel 文档?

问题描述

我正在尝试向 excel 文档添加属性(很少有属性会使文档保密)。我尝试了在互联网上找到的几种方法,但要么出现异常,要么什么也没发生。有人能告诉我我在哪里犯错吗?

  1. 方式:在这里我得到 System.Reflection.TargetParameterCountException。

     class Program
    {
        static Application excelApp;
        static Workbook excelWorkBook;
        static Worksheet excelWorkSheet;

        string name1 = "myprop1";
        string val1 = "myvalue1";

        string name2 = "myprop2";
        string val2 = "myvalue2";

        string name3 = "longid";
        int val3 = 3;

        string name4 = "id";
        int val4 = 2;


        excelWorkBook.CustomDocumentProperties(name1,val1);
        excelWorkBook.CustomDocumentProperties(name2, val2);
        excelWorkBook.CustomDocumentProperties(name3, val3);
        excelWorkBook.CustomDocumentProperties(name4, val4);
    }

  1. 方式:这里什么都没有发生。属性没有改变,也不例外。
 excelWorkSheet.CustomProperties.Add("myprop1", "myvalue1");
 excelWorkSheet.CustomProperties.Add("myprop2", "myvalue2");
 excelWorkSheet.CustomProperties.Add("myprop3", 3);
 excelWorkSheet.CustomProperties.Add("myprop4", 2);
  1. 尝试给我: System.ArgumentException:Value 不在预期范围内。
excelWorkBook.CustomDocumentProperties["myprop1"].Text = "myvalue1";
excelWorkBook.CustomDocumentProperties["myprop2"].Text = "myvalue2";
excelWorkBook.CustomDocumentProperties["myprop3"].Value = 3;
excelWorkBook.CustomDocumentProperties["myprop4"].Value = 2;

标签: c#excelautomationcomoffice-interop

解决方案


对于 c# ,它对我有用,

 

      Microsoft.Office.Core.DocumentProperties prps;
    
       prps = (Office.DocumentProperties)this.CustomDocumentProperties;
       prps.Add("事务类型", false, Microsoft.Office.Core
                .MsoDocProperties.msoPropertyTypeString,“余额”,缺失);

这里“交易类型”是关键,“余额”是价值


推荐阅读