Microsoft.Office.Interop.Excel:如何在一个单元格中应用边框。

11

我希望使用Microsoft.Office.Interop.Excel库向一个单元格应用边框。

我正在运行一个while循环,搜索某一列的空单元格,一旦找到单元格,我想向其应用边框。

我知道有许多使用范围(Ranges)的论坛,但是由于我不知道它被应用到哪个单元格,所以无法使用范围功能。

我的想法是:

(Excel.Range)xlWS.Cells[row,1].Borders.LineStyle = (Whatever Value);

除了链接到其他论坛(我已经浏览了大量的论坛),还有什么建议吗?


你当前的想法有什么问题? - chancea
这更像是一个猜测,多亏了jiverson的帮助,我才能够生成正确的代码来完成它! - Van-Brad
太棒了!如果他的回答解决了你的问题,请务必点击勾选标记以接受它,这样我们就知道这个问题已经得到解决了。 - chancea
4个回答

19
Excel.Range range = xlWS.UsedRange;
Excel.Range cell = range.Cells[row, column];
Excel.Borders border = cell.Borders;

border.LineStyle = Excel.XlLineStyle.xlContinuous;
border.Weight = 2d;

希望这能帮助到有需要的人!在单元格[row,column]周围加上细线边框!


这个按照我的预期工作了。我改变的唯一一件事是 Excel.Range cell = range.Cells; - SubqueryCrunch

14
    Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
    Microsoft.Office.Interop.Excel.Range cell = range.Cells[1][1];
    Microsoft.Office.Interop.Excel.Borders border = cell.Borders;
    border[XlBordersIndex.xlEdgeLeft].LineStyle =
        Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
    border[XlBordersIndex.xlEdgeTop].LineStyle =
        Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
    border[XlBordersIndex.xlEdgeBottom].LineStyle =
        Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
    border[XlBordersIndex.xlEdgeRight].LineStyle =
        Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

请查看答案以获取更多详细信息。


谢谢!使用您的建议,我能够生成相同功能但代码量更少的代码。 - Van-Brad

4

对于范围内的每个单元格

Microsoft.Office.Interop.Excel.Range chartRange;
chartRange = workSheet.get_Range("a1", "g7");
foreach (Microsoft.Office.Interop.Excel.Range cell in chartRange.Cells)
{
    cell.BorderAround2();
}

到整个范围

chartRange.BorderAround2();

我正在寻找这个,谢谢穆罕默德。BorderAround2()为给定范围绘制轮廓。 - imsome1

2

这是基于jiverson的答案,但对于基本需求更加简洁;只需创建一个范围,获取其边框,并在范围底部添加边框:

var platypusRange = _xlSheet.Range[_xlSheet.Cells[1, 1], _xlSheet.Cells[1, 3]];
. . .
Borders border = platypusRange.Borders;
border[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;

当然,你也可以使用xlEdgeTop、xlEdgeLeft和xlEdgeRight将边框添加到顶部和侧面。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接