【问题标题】:How add colourful table to Excel using COM introp?如何使用 COM 互操作将彩色表格添加到 Excel?
【发布时间】:2014-03-26 05:15:47
【问题描述】:

这是我使用 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。

我需要一张这样的彩色桌子

这样的彩色Excel需要做哪些修改?

【问题讨论】:

    标签: c# excel-interop


    【解决方案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。该链接有一个关于如何使用它的示例代码。

    【讨论】:

    • 表格边框可以加粗吗?
    • 用如何设置边框的信息更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2022-11-16
    • 2010-12-25
    • 1970-01-01
    • 2015-08-03
    • 2011-04-11
    • 2016-03-04
    相关资源
    最近更新 更多