2012-10-04 24 views
8

Ich möchte Sie fragen, wie man die Farbe einer Zeile in Excel-Tabelle rot ändert, wenn die Zelle 1 nicht null ist.C# excel, wie man eine Farbe einer bestimmten Zeile ändert

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

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

bin ich

+0

Welche Bibliothek Sie verwenden? –

+0

Microsoft.Office.Interop.Excel –

+0

Ich habe versucht xlWorkSheet.Cells ["A2", "B2"]. Interior.Color = System.Drawing.ColorTranslator.ToOle (System.Drawing.Color.Red); aber es gibt mir Fehler COMException –

Antwort

14

Geben Sie diesem einen Schuss sehr dankbar, ich habe es getestet und es funktioniert:

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

Ich habe Fehler hier: string firstCellValue = firstCell.Value; RuntimeBinderException: kann nicht von Double in String konvertieren –

+2

Ich habe die Antwort geändert – JMK

+0

ok, danke, ich habe es mit 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

Es ist besser, wenn Sie erklären können, wie dies das Problem löst. – Suren

Verwandte Themen