2012-10-04 3 views
8

셀 1이 null이 아니면 Excel 테이블에서 행의 색을 빨간색으로 변경하는 방법을 묻습니다.C# 특정 행의 색을 변경하는 방법을 Excel에서

XX  YY  ZZ 
----------------- 
aa  bb  cc 
aa1 bb1 cc1 
aa2   cc2 
aa3 bb3 cc3 
aa4   

Excel.Application xlApp; 
Excel. Workbook xlWorkBook; 
Excel.Worksheet xlWorkSheet; 

나는 매우

+0

사용하는 라이브러리? –

+0

Microsoft.Office.Interop.Excel –

+0

xlWorkSheet.Cells [ "A2", "B2"]을 시도했습니다. Interior.Color = System.Drawing.ColorTranslator.ToOle (System.Drawing.Color.Red); 하지만 그것은 내게 오류 COMException을 제공합니다 –

답변

14

이 주사를 thankfull, 나는 그것을 테스트 한거야 그것은 작동합니다

Excel.Application application = new Excel.Application(); 
Excel.Workbook workbook = application.Workbooks.Open(@"C:\Test\Whatever.xlsx"); 
Excel.Worksheet worksheet = workbook.ActiveSheet; 

Excel.Range usedRange = worksheet.UsedRange; 

Excel.Range rows = usedRange.Rows; 

int count = 0; 

foreach (Excel.Range row in rows) 
{ 
    if (count > 0) 
    { 
     Excel.Range firstCell = row.Cells[1]; 

     string firstCellValue = firstCell.Value as String; 

     if (!string.IsNullOrEmpty(firstCellValue)) 
     { 
      row.Interior.Color = System.Drawing.Color.Red; 
     } 
    } 

    count++; 
} 

workbook.Save(); 
workbook.Close(); 

application.Quit(); 

Marshal.ReleaseComObject(application); 
+0

나는 여기에 오류있어 : string firstCellValue = firstCell.Value; RuntimeBinderException : double에서 string으로 변환 할 수 없습니다. –

+2

답변을 수정했습니다. – JMK

+0

감사합니다. 나는 convert.toString과 함께했습니다. –

0
Excel.Application xlAppToExport = new Excel.Application(); 
xlAppToExport.Workbooks.Add(""); 
Excel.Worksheet xlWorkSheetToExport = default(Excel.Worksheet); 
xlWorkSheetToExport = (Excel.Worksheet)xlAppToExport.Sheets["Sheet1"]; 

xlWorkSheetToExport.Range["A5:F5"].EntireRow.Interior.Color = System.Drawing.Color.Gray; 
+1

이것이 어떻게 문제를 해결하는지 설명 할 수 있다면 더 좋습니다. – Suren

관련 문제