加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – EPPlus – 按索引而不是按字母表示法处理多个列

发布时间:2020-12-15 07:44:40 所属栏目:百科 来源:网络整理
导读:我在.Net项目中使用EPPlus将一些数据输出到Excel工作表中. 假设我想格式化具有特定格式的列E-G.使用EPPlus,我知道我可以这样做: wks.Cells("E:G").Style.Numberformat.Format = ... 现在,我想知道,假设我想做同样的事情,但是通过他们的索引号而不是字母表示
我在.Net项目中使用EPPlus将一些数据输出到Excel工作表中.

假设我想格式化具有特定格式的列E-G.使用EPPlus,我知道我可以这样做:

wks.Cells("E:G").Style.Numberformat.Format = ...

现在,我想知道,假设我想做同样的事情,但是通过他们的索引号而不是字母表示来引用列 – 理论上看起来像这样:

wks.Columns("5:7").Style.Numberformat.Format = ...

现在,我知道如果我做了这样的事情会有效:

wks.Cells(1,5,wks.Dimension.End.Row,7).Style.Numberformat.Format = ...

但我希望在EPPlus中有更好/更好的方法.有什么想法/建议?

谢谢!!

解决方法

作为我自己的问题的答案,为了帮助任何人,我最终创建了自己的扩展方法列,将列号转换为ExcelRange对象:
''' <summary>
''' Allows you to reference a column by its numeric index rather than its alphabetic representation
''' </summary>
''' <param name="colNum">The index of the column to reference on in the worksheet.</param>
<System.Runtime.CompilerServices.Extension()> _
Public Function Columns(ByVal wks As ExcelWorksheet,ByVal colNum As Integer) As ExcelRange
    Dim ColName As String = ReturnColumnName(colNum)

    Return wks.Cells(ColName & ":" & ColName)
End Function


''' <summary>
''' Allows you to reference a column by its numeric index rather than its alphabetic representation
''' </summary>
''' <param name="StartColNum">The start col num.</param>
''' <param name="EndColNum">The end col num.</param>
<System.Runtime.CompilerServices.Extension()> _
Public Function Columns(ByVal wks As ExcelWorksheet,ByVal StartColNum As Integer,ByVal EndColNum As Integer) As ExcelRange
    Dim StartColName As String = ReturnColumnName(StartColNum)
    Dim EndColName As String = ReturnColumnName(EndColNum)

    Return wks.Cells(StartColName & ":" & EndColName)
End Function



Private Function ReturnColumnName(ByVal colNum As Integer) As String
    Dim d As Integer
    Dim m As Integer
    Dim Name As String

    d = colNum
    Name = ""

    Do While (d > 0)
        m = (d - 1) Mod 26
        Name = Chr(65 + m) + Name
        d = Int((d - m) / 26)
    Loop

    Return Name
End Function

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读