一个Excel电子表格中单元格的填充模式由两种颜色组成:背景颜色和前景颜色。在这里,“前景颜色”这个术语有点误导。它不是字体的颜色,而是图案填充的前景颜色。
例如,如果您用纯色填充单元格的背景,则单元格的相关PatternFill对象的ForegroundColor属性将设置为所选的纯色值,而BackgroundColor对象则设置为系统前景色。PatternFill对象的PatternType属性设置为PatternValues.Solid。
因此,要获取单元格背景(纯色填充)的颜色值,您必须分析相关PatternFill对象的ForegroundColor属性。您必须确定实例表示的“颜色类型”:
1.自动颜色和系统相关颜色
2.索引颜色。
3.ARGB颜色(Alpha、Red、Green和Blue)
4.基于主题的颜色。
5.应用于颜色的色调值。
关于不同的“颜色类型”更多信息,请参见以下link。
请注意,ForegroundColor
和BackgroundColor
类的InnerText
属性的含义取决于颜色类型。例如,在基于主题的颜色的情况下,InnerText
属性设置为索引到ColorScheme
集合中。
以下示例打印电子表格文档中所有单元格的所有背景颜色信息:
public static PatternFill GetCellPatternFill(Cell theCell, SpreadsheetDocument document)
{
WorkbookStylesPart styles = SpreadsheetReader.GetWorkbookStyles(document);
int cellStyleIndex;
if (theCell.StyleIndex == null)
{
cellStyleIndex = 0;
}
else
{
cellStyleIndex = (int)theCell.StyleIndex.Value;
}
CellFormat cellFormat = (CellFormat)styles.Stylesheet.CellFormats.ChildElements[cellStyleIndex];
Fill fill = (Fill)styles.Stylesheet.Fills.ChildElements[(int)cellFormat.FillId.Value];
return fill.PatternFill;
}
private static void PrintColorType(SpreadsheetDocument sd, DocumentFormat.OpenXml.Spreadsheet.ColorType ct)
{
if (ct.Auto != null)
{
Console.Out.WriteLine("System auto color");
}
if (ct.Rgb != null)
{
Console.Out.WriteLine("RGB value -> {0}", ct.Rgb.Value);
}
if (ct.Indexed != null)
{
Console.Out.WriteLine("Indexed color -> {0}", ct.Indexed.Value);
}
if (ct.Theme != null)
{
Console.Out.WriteLine("Theme -> {0}", ct.Theme.Value);
Color2Type c2t = (Color2Type)sd.WorkbookPart.ThemePart.Theme.ThemeElements.ColorScheme.ChildElements[(int)ct.Theme.Value];
Console.Out.WriteLine("RGB color model hex -> {0}", c2t.RgbColorModelHex.Val);
}
if (ct.Tint != null)
{
Console.Out.WriteLine("Tint value -> {0}", ct.Tint.Value);
}
}
static void ReadAllBackgroundColors()
{
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open("c:\\temp\\bgcolor.xlsx", false))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
foreach(WorksheetPart worksheetPart in workbookPart.WorksheetParts)
{
SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
foreach (Row r in sheetData.Elements<Row>())
{
foreach (Cell c in r.Elements<Cell>())
{
Console.Out.WriteLine("----------------");
PatternFill pf = GetCellPatternFill(c, spreadsheetDocument);
Console.Out.WriteLine("Pattern fill type -> {0}", pf.PatternType.Value);
if (pf.PatternType == PatternValues.None)
{
Console.Out.WriteLine("No fill color specified");
continue;
}
Console.Out.WriteLine("Summary foreground color:");
PrintColorType(spreadsheetDocument, pf.ForegroundColor);
Console.Out.WriteLine("Summary background color:");
PrintColorType(spreadsheetDocument, pf.BackgroundColor);
}
}
}
}
}
static void Main(string[] args)
{
ReadAllBackgroundColors();
}