2012-05-25 4 views
6

Excel의 스프레드 시트에서 셀의 배경색을 가져 오려고합니다. Open XML 2.0 SDK를 사용하고 있으며 * .xlsx 파일을 열고 셀 값을 가져올 수 있습니다. 단지 자연수 PatternFill.BackgroundColor 반환, 나는 그것이 스타일의 ID의 생각, 여기Open XML 2.0을 사용하여 Excel에서 cell-backgroundcolor 가져 오기

public BackgroundColor GetCellBackColor(Cell theCell, SpreadsheetDocument document) 
    { 
     BackgroundColor backGroundColor = null; 
     WorkbookStylesPart styles = SpreadsheetReader.GetWorkbookStyles(document); 
     int cellStyleIndex = (int)theCell.StyleIndex.Value; 
     CellFormat cellFormat = (CellFormat)styles.Stylesheet.CellFormats.ChildElements[cellStyleIndex]; 
     Fill fill = (Fill)styles.Stylesheet.Fills.ChildElements[(int)cellFormat.FillId.Value]; 
     backGroundColor = fill.PatternFill.BackgroundColor; 

     return backGroundColor; 
    } 

내 문제 : 배경색을 얻기를위한 내 코드는 다음과 같다. 아닌 자기가 정의 - 내 문제는 Stylesheet.Colorsnull 때문에 나는 Excel에서 색 "내장"사용하기 때문에 코드 오류와

DocumentFormat.OpenXml.Spreadsheet.Color c = (DocumentFormat.OpenXml.Spreadsheet.Color)styles.Stylesheet.Colors.ChildElements[Int32.Parse(backGroundColor.InnerText)]; 

반환 라인이 ... ... 어쩌면이 있다고한다 색깔?!

"backGroundColor-Value"에서 실제 색상 수를 "계산할"수있는 아이디어가 있습니까?

+0

클래스 SpreadsheetReader가 아닌 좋은 답변을 주셔서 감사합니다 OpenXML을 2.5 – Elmue

답변

10

엑셀 스프레드 시트의 셀 채우기 패턴은 배경색과 전경색의 두 가지 색상으로 구성된 입니다. 전경 색상이라는 용어는 여기에서 약간 오도합니다. 폰트의 색은 이 아니지만 패턴 채우기의 전경색입니다. 만약 단색 가 BackgroundColor 객체 가 시스템에 설정되어은 선택된 단색 값으로 설정된 셀의 releated PatternFill 객체 ForegroundColor 속성 셀의 배경을 채울 경우, 예를 들어

전경색. PatternFill 개체의 PatternType 속성은 PatternValues.Solid으로 설정됩니다.

따라서 셀 배경 (채우기 색)의 색상 값을 얻으려면 관련 PatternFill 개체의 ForegroundColor 속성 인 을 분석해야합니다. 당신은 "컬러의 유형을"결정 에있는 인스턴스를 나타냅니다

  1. 자동 색상 및 시스템에 의존 색상
  2. 있는 인덱스 색상.
  3. ARGB 색상 (알파, 레드, 녹색 및 파랑)
  4. 테마 기반 색상입니다.
  5. 색에 적용된 색조 값입니다.

"색 종류"에 대한 자세한 내용은 link을 참조하십시오.

ForegroundColorBackgroundColor 클래스의 InnerText 속성의 의미는 색상 유형에 따라 다릅니다. 예를 들어 테마 기반 색상의 경우 InnerText 속성 은 ColorScheme 컬렉션의 인덱스로 설정됩니다.

다음은 스프레드 시트 문서의 모든 셀에 대한 모든 배경 색상 정보를 인쇄합니다

public static PatternFill GetCellPatternFill(Cell theCell, SpreadsheetDocument document) 
{ 
    WorkbookStylesPart styles = SpreadsheetReader.GetWorkbookStyles(document); 

    int cellStyleIndex; 
    if (theCell.StyleIndex == null) // I think (from testing) if the StyleIndex is null 
    {        // then this means use cell style index 0. 
    cellStyleIndex = 0;   // However I did not found it in the open xml 
    }        // specification. 
    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); 

    //IndexedColors ic = (IndexedColors)styles.Stylesheet.Colors.IndexedColors.ChildElements[(int)bgc.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(); 
} 
+0

에 존재 않습니다.추가 할 포인트가 하나뿐입니다. 셀의 스타일을 변경하지 않으면'int cellStyleIndex = (int) theCell.StyleIndex.Value; '라인이 null 예외를 발생시킵니다. 이것이 실제로 기본 스타일이고 "어떤"스타일 (색상 등)인지 어떻게 알 수 있습니까? 미리 Thx! – basti

+1

@chiffre : StyleIndex가 null 인 경우 셀 스타일 인덱스 0을 사용해야한다고 생각합니다 (테스트를 한 것 같습니다). 그러나 open xml 사양에서 노트를 찾지 못했습니다. – Hans

+0

그 정보를 제공해 주셔서 감사합니다. 실제로 "cell.GetColor"등등을 호출 할 수있는 좋은 랩퍼가 필요합니다. (실제로 작동합니다;) – basti

관련 문제