2016-08-19 89 views
1

Excel电子表格到色单元的一整列下面是我使用色单元在Excel文件中使用NPOI C#程序:尝试使用NPOI

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:

enter image description here

我在做什么错?

回答

2

的问题是这一行:

dataRow.Cells[9].CellStyle = hStyle; 

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

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

尝试改变问题的行这样的:

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

顺便说一句,我注意到你正在为每一个小区的全新样式对象,即使样式属性是每个都一样。通常,您不应该这样做,因为Excel只能处理有限数量的样式(根据Excel Specifications and Limits文档,最高可达64,000)。相反,您只应创建新的样式对象,其中实际的样式属性会有所不同,然后在您希望具有相同样式的所有单元格中共享它们。

换句话说,移动你的HSTYLE对象的创建循环像这样外:

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; 
}