2012-10-04 68 views
8

我想問你們,如果單元格1不爲空,如何在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

給這個一杆,我已經測試它和它的作品:

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:無法從雙倍轉換爲字符串 –

+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