如何使用 F# 中的 NPOI 将单元格的颜色更改为用户定义的值,同时保持其现有样式?

问题描述 投票:0回答:1

如何使用 F# 中的 NPOI 将单元格颜色设置为用户定义的值?线程中提供的答案解决了如何使用 F# 设置正确属性的问题,但它使用了新的

ICellStyle
对象并覆盖了现有的风格。

重写函数(见下文)以直接设置现有单元格的样式属性会产生副作用,即使用相同的颜色绘制工作表中的大多数单元格。

let changeCellColorDirectly (cell: ICell) (rgb: byte array) =
    let xssfCell = cell :?> NPOI.XSSF.UserModel.XSSFCell
    match xssfCell.CellStyle with
    | :? NPOI.XSSF.UserModel.XSSFCellStyle as xssfCellStyle ->
        let color = new NPOI.XSSF.UserModel.XSSFColor(rgb)
        xssfCellStyle.FillForegroundXSSFColor <- color
        xssfCellStyle.FillPattern <- NPOI.SS.UserModel.FillPattern.SolidForeground
    | _ -> failwith "'newCellStyle' cannot be cast to XSSFCellStyle"

我假设相同样式的单元格共享相同的

ICellStyle
对象,所以我尝试用
ICellStyle
CloneStyleFrom
方法解决这个问题(见下文),但结果是相同的。

let changeCellColorByCloning (cell: ICell) (rgb: byte array) =
    let xssfCell: NPOI.XSSF.UserModel.XSSFCell = cell :?> NPOI.XSSF.UserModel.XSSFCell
    let newCellStyle: NPOI.SS.UserModel.ICellStyle = xssfCell.Sheet.Workbook.CreateCellStyle()
    newCellStyle.CloneStyleFrom(xssfCell.CellStyle)
    match newCellStyle with
    | :? NPOI.XSSF.UserModel.XSSFCellStyle as xssfCellStyle ->
        let color = new NPOI.XSSF.UserModel.XSSFColor(rgb)
        xssfCellStyle.FillForegroundXSSFColor <- color
        xssfCellStyle.FillPattern <- NPOI.SS.UserModel.FillPattern.SolidForeground
    | _ -> failwith "'newCellStyle' cannot be cast to XSSFCellStyle"
    xssfCell.CellStyle <- newCellStyle
excel f# npoi
1个回答
0
投票

通过编写我自己的克隆函数解决了这个问题:

open System.Reflection

let cloneCellStyle (cell: NPOI.XSSF.UserModel.XSSFCell)  =
    let original = cell.CellStyle
    let copy: NPOI.SS.UserModel.ICellStyle = cell.Sheet.Workbook.CreateCellStyle()
    let properties = original.GetType().GetProperties(BindingFlags.Public ||| BindingFlags.Instance)
    for prop in properties do
        if prop.CanRead && prop.CanWrite then
            let value = prop.GetValue(original)
            prop.SetValue(copy, value)
    copy

let changeCellColor (cell: ICell) (rgb: byte array) =
    let xssfCell: NPOI.XSSF.UserModel.XSSFCell = cell :?> NPOI.XSSF.UserModel.XSSFCell
    let newCellStyle: NPOI.SS.UserModel.ICellStyle = cloneCellStyle xssfCell
    // newCellStyle.CloneStyleFrom(xssfCell.CellStyle)
    match newCellStyle with
    // match xssfCell.CellStyle with
    | :? NPOI.XSSF.UserModel.XSSFCellStyle as xssfCellStyle ->
        let color = new NPOI.XSSF.UserModel.XSSFColor(rgb)
        xssfCellStyle.FillForegroundXSSFColor <- color
        xssfCellStyle.FillPattern <- NPOI.SS.UserModel.FillPattern.SolidForeground
    | _ -> failwith "'newCellStyle' cannot be cast to XSSFCellStyle"
    xssfCell.CellStyle <- newCellStyle

请参阅上面链接的线程了解如何使用。

© www.soinside.com 2019 - 2024. All rights reserved.