如何使用C#在Excel中的多个单元格周围设置边框

时间:2012-07-31 15:37:13

标签: c# excel border

我正在开发一个创建excel文件的项目。

我在多个单元格上放置边框以组织excel文件时遇到问题。

假设我想要从B5到B10的边界。 B5,B6,B7之间不应该有边界......

目前,我有这段代码:

workSheet_range = worksheet.get_Range("B5", "B10");
workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();

它会生成边框,但是它会在每个单元格周围放置边框,而不是为所有单元格设置一个大边框。

我怎样才能做到这一点?

8 个答案:

答案 0 :(得分:13)

您需要单独设置这些

.Borders[Excel.XlBordersIndex.xlEdgeBottom] 
.Borders[Excel.XlBordersIndex.xlEdgeRight]
.Borders[Excel.XlBordersIndex.xlEdgeLeft]  
.Borders[Excel.XlBordersIndex.xlEdgeTop]

答案 1 :(得分:8)

也许这会有所帮助:

workSheet_range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThick);

答案 2 :(得分:4)

这是在每个单元格周围设置边框的代码:

xlWS.get_Range("C9", "N9").Cells.Borders.Weight = XL.XlBorderWeight.xlMedium;

答案 3 :(得分:2)

我这样做没有影响性能。我正在采用一个简单的格式来格式化:

之前

enter image description here

我设法将范围A1:C4动态地存储在 exRange 中的变量中,并使用下面的代码来提供边框

((Range)excelSheet.get_Range(exRange)).Cells.Borders.LineStyle = XlLineStyle.xlContinuous;


enter image description here

答案 4 :(得分:0)

// ** - You Should do it in all Cells 

//BorderAround: Medium**

worksheet.get_Range("b5", "b5").Cells.BorderAround(Missing.Value, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, ColorTranslator.ToOle(Color.FromArgb(255, 192, 0)));

worksheet.get_Range("b6", "b6").Cells.BorderAround(Missing.Value, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, ColorTranslator.ToOle(Color.FromArgb(255, 192, 0)));

worksheet.get_Range("b10", "b10").Cells.BorderAround(Missing.Value, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, ColorTranslator.ToOle(Color.FromArgb(255, 192, 0)));        

答案 5 :(得分:0)

此代码在(row1,col1)到(row2,col2)区域周围放置边框。单个细胞没有边界。可变颜色是整数颜色索引号。请参阅http://www.databison.com/excel-color-palette-and-color-index-change-using-vba/以获取索引编号及其相应颜色的列表。

    Range cell1 = worksheet.Cells[row1,col1];
    Range cell2 = worksheet.Cells[row2,col2];
    Range range = worksheet.get_Range(cell1,cell2);
    range.BorderAround(
        Type.Missing, XlBorderWeight.xlThick, (XlColorIndex)color, Type.Missing );

答案 6 :(得分:0)

ws.UsedRange.BorderAround(
                        Xl.XlLineStyle.xlDash,
                        Xl.XlBorderWeight.xlThick,
                        Xl.XlColorIndex.xlColorIndexAutomatic,
                        ColorTranslator.ToOle(Color.Blue));

答案 7 :(得分:0)

这是我的解决方案,只使用UsedRange()函数

Excel.Range tRange = oSheet.UsedRange;
            tRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
            tRange.Borders.Weight = Excel.XlBorderWeight.xlThin;