尝试使用NPOI在Excel电子表格中对整列单元格着色

下面是我用来使用NPOI在Excel文件中对单元格进行着色的C#程序:

string pathSource = @"C:\Users\mvmurthy\Downloads\VOExportTemplate (2).xlsx"; HSSFWorkbook templateWorkbook; HSSFSheet sheet; HSSFRow dataRow; using (var fs = new FileStream(pathSource, FileMode.Open, FileAccess.ReadWrite)) { templateWorkbook = new HSSFWorkbook(fs, true); sheet = (HSSFSheet)templateWorkbook.GetSheet("ImportTemplate"); int num = sheet.PhysicalNumberOfRows; for (int i=1; i<num; i++) { dataRow = (HSSFRow)sheet.GetRow(i); HSSFCellStyle hStyle = (HSSFCellStyle)templateWorkbook.CreateCellStyle(); hStyle = (HSSFCellStyle)templateWorkbook.CreateCellStyle(); hStyle.FillForegroundColor = IndexedColors.Red.Index; hStyle.FillPattern = FillPattern.SolidForeground; dataRow.Cells[9].CellStyle = hStyle; } } using (var fs = new FileStream(pathSource, FileMode.Open, FileAccess.ReadWrite)) { templateWorkbook.Write(fs); } 

当我运行上面的代码时,我得到以下输出,但我想只给K列着色:

在这里输入图像说明

我究竟做错了什么?

问题是这一行:

 dataRow.Cells[9].CellStyle = hStyle; 

Cells[n]忽略空单元,所以这将得到第10个(从0开始的)非空单元。 在屏幕截图中,第三行和第四行在Description列中有一个值,所以第十个非空单元格在J列中,而对于其余行,则在第K列中。

如果您想要通过特定的列获取单元格,则应该使用GetCell(n) 。 但是请注意,如果该列中没有单元格,则默认情况下会返回空值。 如果需要的话,你可以传递第二个参数给这个方法来指定它应该在那种情况下创build一个新的单元而不是返回null。

尝试将有问题的行更改为:

 dataRow.GetCell(10, MissingCellPolicy.CREATE_NULL_AS_BLANK).CellStyle = hStyle; 

顺便说一句,我注意到你正在为每个单元格创build一个全新的样式对象,即使样式属性都是相同的。 一般来说,您不应该这样做,因为Excel只能处理有限数量的样式(根据Excel规范和限制文档,最多可达64,000个样式)。 相反,您应该只在实际样式属性不同的情况下创build新的样式对象,然后在所有希望具有相同样式的单元格中共享它们。

换句话说,像这样在循环之外移动你的hStyle对象的创build:

 HSSFCellStyle hStyle = (HSSFCellStyle)templateWorkbook.CreateCellStyle(); hStyle.FillForegroundColor = IndexedColors.Red.Index; hStyle.FillPattern = FillPattern.SolidForeground; for (int i = 1; i < num; i++) { dataRow = (HSSFRow)sheet.GetRow(i); dataRow.GetCell(10, MissingCellPolicy.CREATE_NULL_AS_BLANK).CellStyle = hStyle; }