如何使用COM introp将彩色表添加到Excel?

时间:2014-03-26 05:15:47

标签: c# excel-interop

这是我使用COM互操作生成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?

2 个答案:

答案 0 :(得分:1)

不知道这是否是你需要的,但它会给你一些想法。 看一下给定的链接

Excel table Color

答案 1 :(得分:1)

您需要为每个单元格设置字体颜色和背景颜色。您已经将字体设置为粗体:

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

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

在VBA中,您可以使用RGB值指定字体:

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

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

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