2017-11-13 150 views
0

セルのフォント色を条件付きで変更しようとしています。これは私の最後の試行です:NPOIはセルのフォント色を変更しません

IWorkbook wb = null; 

using (FileStream _fileStream = new FileStream(path, FileMode.Open, FileAccess.Read)) 
{ 
    wb = WorkbookFactory.Create(_fileStream); 
    _fileStream.Close(); 
} 



ISheet sheet = wb.GetSheet(sheetName); 
IFont font = wb.CreateFont(); 
... 
... 

// within a loop 
ICell cell = sheet.GetRow(r).GetCell(col); 
if (integrity < 1) 
{ 
    ICellStyle redStyle = cell.CellStyle; 
    font.Color = IndexedColors.Red.Index; 
    redStyle.SetFont(font); 
    cell.CellStyle = redStyle; 
} 
else 
{ 
    ICellStyle normalStyle = cell.CellStyle; 
    font.Color = XSSFFont.DEFAULT_FONT_COLOR; 
    normalStyle.SetFont(font); 
    cell.CellStyle = normalStyle; 
}       

ただし、条件が満たされてもフォントは変更されません。ループの中に入っているセルの代わりに、すべてのセルにスタイルが適用されているようです。私はこの問題に関連するいくつかの質問を読んだが、うまくいかない。

この新しい試みはすべてのセルをフォーマットしています。それが条件またはデフォルトで「normalStyle」

答えて

0

ですべてのセルの書式を設定でしょうない

ICellStyle redStyle = cell.CellStyle; 
font.Color = IndexedColors.Red.Index;    
redStyle.SetFont(font);  

//This is how I am trying to change cells format 
if (integrity < 1) 
{ 
    cell.CellStyle.SetFont(font); 
} 

ジョアン応答を満たしているかどうかに関係なく、すべてのセルは同じCellStyleオブジェクトを使用することになります。異なるセルに異なるスタイルを使用する場合は、別個のオブジェクトを作成する必要があります。

ICellStyle redStyle = wb.CreateCellStyle(); 
font.Color = IndexedColors.Red.Index; 
redStyle.SetFont(font); 

ICellStyle normalStyle = wb.CreateCellStyle(); 
font.Color = XSSFFont.DEFAULT_FONT_COLOR; 
normalStyle.SetFont(font); 

// within a loop 
ICell cell = sheet.GetRow(r).GetCell(col); 
if (integrity < 1) 
{ 
    cell.CellStyle = redStyle; 
} 
else 
{ 
    cell.CellStyle = normalStyle; 
}       

(注:。。。正しい方向に私がすべてでこのコードをテストしていない私はCreateCellStyleがそのように動作するかどうかを忘れしかし、それが必要、少なくともポイントあなたは)

+0

おかげでそれを割り当てます!しかし、期待どおりに動作していません。私はあなたの応答に基づいて私の最後の試行で私の質問を編集しました –

+0

あなたの編集はおそらく動作できません。私のコードはICellStyleオブジェクトをループの外側に作成し、ワークブックから直接作成することに注意してください。 'cell.CellStyle'プロパティにアクセスしてそのプロパティを変更することはできません。そうしないと、常に同じオブジェクトで作業することになります。 –

0

だから私は定義してしまいます私が条件を満たす細胞に設定しておくスタイル。

IFont redfont = wb.CreateFont(); 
redfont.Color = IndexedColors.Red.Index; 
redfont.FontHeight = 8; 
ICellStyle style = wb.CreateCellStyle(); 

... 
if (integrity < 1) 
{ 
    style.CloneStyleFrom(cell.CellStyle); 
    style.SetFont(redfont); 
    cell.CellStyle = style; 
} 

ありがとうございます!

0

はXSSF形式のフォントを作成するには、このアプローチを使用して、細胞

にyouir応答のための
XSSFFont defaultFont = (XSSFFont)workbook.CreateFont(); 
defaultFont.FontHeightInPoints = (short)10; 
defaultFont.FontName = "Arial"; 
defaultFont.Color = IndexedColors.Black.Index; 
defaultFont.IsBold = false; 
defaultFont.IsItalic = false; 
defaultFont.Boldweight = 700; 

XSSFCellStyle defaultStyle = (XSSFCellStyle)workbook.CreateCellStyle(); 
defaultStyle.SetFont(defaultFont); 
関連する問題