首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用NPOI改变细胞颜色

如何用NPOI改变细胞颜色
EN

Stack Overflow用户
提问于 2016-05-05 13:48:31
回答 1查看 43.4K关注 0票数 24
代码语言:javascript
复制
using NPOI.XSSF.UserModel;
using NPOI.XSSF.Model;

using NPOI.HSSF.UserModel;
using NPOI.HSSF.Model;

using NPOI.SS.UserModel;
using NPOI.SS.Util;


(...)

XSSFWorkbook hssfwb;

using (FileStream file = new FileStream(@"D:\VB\XLSX teste com NPOI\XLSX 1\Book1.xlsx", 
     FileMode.Open, FileAccess.Read))
{
    hssfwb = new XSSFWorkbook(file);
    file.Close();
}

ISheet sheet = hssfwb.GetSheetAt(0);
IRow row = sheet.GetRow(0);

ICell cell = row.CreateCell(5);
cell.SetCellValue("test");
cell.CellStyle.FillBackgroundColor = IndexedColors.BrightGreen.Index;
cell.CellStyle.FillPattern = FillPattern.SolidForeground;

using (FileStream file = new FileStream(@"D:\VB\XLSX teste com NPOI\XLSX 1\Book1ee22.xlsx", 
     FileMode.Create, FileAccess.Write))
{
    hssfwb.Write(file);
    file.Close();
}

版本的NPOI: 2.1.3.1我有这个代码,它正在改变颜色的孔板,而不仅仅是细胞.改变单元格填充颜色的正确方法是什么?

以下是基于下面标记为正确的答案的工作代码:

代码语言:javascript
复制
XSSFWorkbook hssfwb;
        using (FileStream file = new FileStream(@"D:\Copy D\Tech\VB\XLSX teste com NPOI\XLSX 1\Book1.xlsx", FileMode.Open, FileAccess.Read))
        {
            hssfwb = new XSSFWorkbook(file);
            file.Close();
        }

        ISheet sheet = hssfwb.GetSheetAt(0);
        IRow row = sheet.GetRow(0);


        ICellStyle testeStyle = hssfwb.CreateCellStyle();
        testeStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
        testeStyle.FillForegroundColor = IndexedColors.BrightGreen.Index;
        testeStyle.FillPattern = FillPattern.SolidForeground;


        ICell cell = row.CreateCell(5);
        cell.SetCellValue("testeeerere");
        cell.CellStyle = testeStyle;


        using (FileStream file = new FileStream(@"D:\Copy D\Tech\VB\XLSX teste com NPOI\XLSX 1\Book1ee22.xlsx", FileMode.Create, FileAccess.Write))
        {
            hssfwb.Write(file);
            file.Close();
        }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-05 13:51:49

看一下这个例子:

代码语言:javascript
复制
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;

(...)

代码语言:javascript
复制
Row row = sheet.CreateRow(0);

//styling
Font boldFont = workbook.CreateFont();
boldFont.Boldweight = (short)FontBoldWeight.BOLD;
ICellStyle boldStyle = workbook.CreateCellStyle();
boldStyle.SetFont(boldFont);

boldStyle.BorderBottom = CellBorderType.MEDIUM;
boldStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.GREY_25_PERCENT.index;
boldStyle.FillPattern = FillPatternType.SOLID_FOREGROUND;


for (int i = 0; i < columns.Length; i++)
{
    Cell cell = row.CreateCell(i);
    cell.SetCellValue(columns[i]);
    cell.CellStyle = boldStyle;
}

在这里,您可以看到如何为一行中的每个单元格应用粗体、背景色和边框。在本例中,columns是表示列数据的字符串数组;而是使用您的值。

票数 31
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37052352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档