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

我正在创build一个创buildexcel文件的项目。

我无法在多个单元格上放置边框来组织Excel文件。

比方说,我想要一个从单元格B5到B10的边框。 B5,B6,B7之间不应该有边界

目前,我有这样的代码:

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

它使边界,然而它放置在每个单元格的边界,而不是所有单元格的一个大边框。

我怎样才能做到这一点?

你需要单独设置这些

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

也许这可以帮助:

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

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

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

我做了这个,没有影响性能。 我正在采取一个简单的Excel格式:

之前

在这里输入图像说明

我设法将范围以A1:C4的formsdynamic存储在exRange中,并使用下面的代码给出边界

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

在这里输入图像说明

 // ** - 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))); 

此代码从(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 ); 
 ws.UsedRange.BorderAround( Xl.XlLineStyle.xlDash, Xl.XlBorderWeight.xlThick, Xl.XlColorIndex.xlColorIndexAutomatic, ColorTranslator.ToOle(Color.Blue)); 

这里是我的解决scheme,使用简单的UsedRange()函数

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