如何从 C# 设置 Excel 颜色主题(例如使用 Microsoft.Office.Interop.Excel)?

问题描述 投票:0回答:1

我们有一个企业配色方案,它会作为页面布局 > 颜色 > [customNameHere] 中的自定义颜色集合自动包含在所有用户计算机上。

我有一个加载项(作为其他任务负载的一部分)需要对用户选择的任意 Excel 工作簿进行一些配置 - 实际上是给定工作簿的“设置”按钮。有没有办法从我的 C# 代码中查找此 [customNameHere] 颜色主题是否存在,然后将工作簿设置为使用该主题(如果存在)?

我尝试在互联网上搜索答案的开头,但我不确定要搜索什么!

我目前正在使用 ExcelDNA 中的几种方法来与 Excel 进行性能关键型交互,但大多数情况下只是使用 Interop 程序集来执行此类任务,这些任务频率较低且对性能不是关键型。

假设我已经设置了对相关 Workbook 对象的引用,并且想要查找主题颜色,我想要如下所示的内容:

using xl = Microsoft.Office.Interop.Excel;

[...]
xl.Workbook wb = // some code to set the Workbook object - too complex to include here

// What method do I use on wb object to, for example, set the theme to Grayscale, as this is one of the built-in themes that you will all have access to?
wb.???.???.??? = "Grayscale"

大概我会将该代码包装在我的公司颜色主题的 try 语句中,以处理由于某种原因该代码不存在于特定用户计算机上的情况。

c# excel
1个回答
0
投票
using xl = Microsoft.Office.Interop.Excel;

xl.Workbook wb = // code to set the Workbook object

string customColorTheme = "[customNameHere]";

bool themeExists = false;
foreach (xl.Theme theme in wb.ThemeNames)
{
    if (theme.Name == customColorTheme)
    {
        themeExists = true;
        break;
    }
}

if (themeExists)
{
    xl.Worksheet activeSheet = (xl.Worksheet)wb.ActiveSheet;
    activeSheet.EnableThemeFont = true;
    activeSheet.EnableThemeFormatting = true;
    activeSheet.Theme = customColorTheme;
}
else
{
    // Handle the case where the custom color theme does not exist in the workbook
}

此代码片段迭代工作簿中的可用主题并检查自定义颜色主题是否存在。如果是,它将启用活动工作表的主题字体和格式并将主题设置为自定义颜色主题。

© www.soinside.com 2019 - 2024. All rights reserved.