2012-10-04 27 views
8

Tôi muốn hỏi các bạn, cách thay đổi màu của một hàng thành màu đỏ trong bảng Excel nếu ô 1 không phải là rỗng.C# excel cách thay đổi màu của một hàng cụ thể

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

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

Tôi rất thankfull

+0

Những thư viện bạn đang sử dụng? –

+0

Microsoft.Office.Interop.Excel –

+0

Tôi đã thử xlWorkSheet.Cells ["A2", "B2"]. Interior.Color = System.Drawing.ColorTranslator.ToOle (System.Drawing.Color.Red); nhưng nó mang lại cho tôi lỗi COMException –

Trả lời

14

này cung cấp cho một shot, tôi đã thử nghiệm nó và nó hoạt động:

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

Tôi đã có lỗi ở đây: string firstCellValue = firstCell.Value; RuntimeBinderException: không thể chuyển đổi từ đôi thành chuỗi –

+2

Tôi đã sửa đổi câu trả lời – JMK

+0

ok, cảm ơn, tôi đã làm điều đó với 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

Sẽ tốt hơn nếu bạn có thể giải thích cách giải quyết vấn đề này. – Suren

Các vấn đề liên quan