2012-10-04 121 views
8

Quiero preguntarles a ustedes, cómo cambiar el color de una fila a rojo en la tabla de Excel si la celda 1 no es nula.C# excel cómo cambiar el color de una fila particular

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

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

estoy muy thankfull

+0

qué biblioteca está utilizando? –

+0

Microsoft.Office.Interop.Excel –

+0

He intentado con xlWorkSheet.Cells ["A2", "B2"]. Interior.Color = System.Drawing.ColorTranslator.ToOle (System.Drawing.Color.Red); pero me da error COMException –

Respuesta

14

dar a este un tiro, yo lo he probado y funciona:

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

Tengo error aquí: string firstCellValue = firstCell.Value; RuntimeBinderException: no se puede convertir de doble a cadena –

+2

He modificado la respuesta – JMK

+0

bien, gracias, lo hice con 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 mejor si puedes explicar cómo esto resuelve el problema. – Suren

Cuestiones relacionadas