代码之家  ›  专栏  ›  技术社区  ›  KGB91

将XlLineStyle用作对象C#

  •  0
  • KGB91  · 技术社区  · 6 年前

    我有一个代码,根据字符串中的值,在Excel表格中的单元格周围画一条线, border :

        if (border != null)
        {
            //can be one or serval of below
            if (border.Contains("Bottom"))
                workSheet.Cells[i, j].Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            if (border.Contains("Right"))
                workSheet.Cells[i, j].Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            if (border.Contains("Left"))
                workSheet.Cells[i, j].Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            if (border.Contains("Top"))
                workSheet.Cells[i, j].Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }
    

    现在我想添加一个新变量, string linetype ,这决定了行:

            if (linetype == "Double")
                lineobject = XlLineStyle.xlDouble;
    

    这样我就可以写:

    workSheet.Cells[i, j].Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = lineobject;
    

    添加字符串当然很容易。但我不知道如何定义 lineobject 因此,我可以在以后使用特定的线型,而不必为我想用于该行所有四个位置的每种线型重写这里的第一部分代码。

    0 回复  |  直到 6 年前
        1
  •  1
  •   user2316116    6 年前

    当然,没有办法定义自定义边框(在Excel UI中,您还需要单独选择线条、颜色和宽度),但LineStyle/lineobject可以很容易地分配到一些变量

    var cell = worksheet.Cells[2, 2];
    var border = cell.Borders;
    
    var myborderstyle = XlLineStyle.xlDash;
    var myborderweight = 4d;
    
    border.LineStyle = myborderstyle;  <-- set specific linetype
    border.Weight = myborderweight;    <-- set specific width
    
    推荐文章