2014-03-26 92 views
1

这是我使用COM interop生成Excel的代码。如何使用COM introp将丰富多彩的表格添加到Excel中?

public static void ExportDataTableToExcel(DataTable dt, string filepath) 
{ 
     object missing = Type.Missing; 
     object misValue = System.Reflection.Missing.Value; 

     //create excel 
     Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); 

     //add excel workbook 
     Microsoft.Office.Interop.Excel.Workbook wb = excel.Workbooks.Add(); 

     //add worksheet to worlbook 
     Microsoft.Office.Interop.Excel.Worksheet ws = wb.Sheets[1] as Microsoft.Office.Interop.Excel.Worksheet; 

     //Set the header-row bold 
     ws.Range["A1", "A1"].EntireRow.Font.Bold = true; 

     //Adjust all columns 
     ws.Columns.AutoFit(); 

     //spit top row 
     ws.Application.ActiveWindow.SplitRow = 1; 

     //freeze top row 
     ws.Application.ActiveWindow.FreezePanes = true; 

     int rowCount = 1; 

     foreach (DataRow dr in dt.Rows) 
     { 
      rowCount += 1; 

      for (int i = 1; i < dt.Columns.Count + 1; i++) 
      { 
       // Add the header the first time through 
       if (rowCount == 2) 
       { 
        ws.Cells[1, i] = dt.Columns[i - 1].ColumnName; 
       } 

       ws.Cells[rowCount, i] = dr[i - 1].ToString(); 
      } 
     } 

     wb.SaveAs(@"C:\ErangaExcelTest.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, 
              misValue, misValue, misValue, 
              Excel.XlSaveAsAccessMode.xlExclusive, misValue, 
              misValue, misValue, misValue, misValue); 

     wb.Close(missing, missing, missing); 

     excel.Quit(); 
    } 

这是我从这种方法得到的Excel。

enter image description here

我需要一个丰富多彩的表像这样

enter image description here

什么样的修改,做我需要做的有这种丰富多彩的Excel的?

回答

1

你需要设置字体颜色和每个单元的背景色。您已将字体设置为粗体显示:

ws.Range["A1", "A1"].EntireRow.Font.Bold = true; 

现在Font对象具有更多属性。要设置字体颜色,请使用Range.Font.Color property。要设置单元格的背景颜色,请参阅Range.Interior property。具体而言,您希望将Pattern设置为xlPatternSolid,然后使用Interior对象的Color属性设置某种颜色。

在VBA中,你可以与他们的RGB值指定的字体:

range.Font.Color = RGB(255, 0, 0) 

将范围的字体颜色设置为红色。

要更改边框,请使用Range.Borders property。该链接有一个关于如何使用它的示例代码。

+1

是否可以加粗表格边框? –

+0

更新了有关如何设置边框的信息。 –

相关问题