Why is EPPlus telling me that I "Can't set color when patterntype is not set" when I have set PatternType?

B. Clay Shannon picture B. Clay Shannon · Jul 29, 2016 · Viewed 17.4k times · Source

I've got this code to try to style a header row:

worksheet.Cells["A32:D32"].Style.Font.Name = "Georgia";
worksheet.Cells["A32:D32"].Style.Font.Bold = true;
worksheet.Cells["A32:D32"].Style.Font.Size = 16;
worksheet.Cells["A32:D32"].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells["A32:D33"].Style.Fill.BackgroundColor.SetColor(Color.CornflowerBlue);

It fails on the last line above with "System.ArgumentException was unhandled. . .Message=Can't set color when patterntype is not set. Source=EPPlus. . ."

What could the real problem be? I am doing what it claimes I'm not, right?

For more context:

worksheet.Cells["A32"].LoadFromCollection(bookDataList, true);
// style header row
worksheet.Cells["A32:D32"].Style.Font.Name = "Georgia";
worksheet.Cells["A32:D32"].Style.Font.Bold = true;
worksheet.Cells["A32:D32"].Style.Font.Size = 16;
worksheet.Cells["A32:D32"].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells["A32:D33"].Style.Fill.BackgroundColor.SetColor(Color.CornflowerBlue);
// style the rest
worksheet.Cells["A33:D59"].Style.Font.Name = "Candara";
worksheet.Cells["A33:D59"].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells["A33:D59"].Style.Fill.BackgroundColor.SetColor(Color.Cornsilk);

Note that I had the "style the rest" code prior to adding the "style header row" and did not run into this problem. The code is exactly the same as to setting PatternType and then BackgroundColor (except for the color used, and the range of cells the code is applied to).

Answer

Ernie S picture Ernie S · Aug 1, 2016

Look closely at the two lines:

worksheet.Cells["A32:D32"].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells["A32:D33"].Style.Fill.BackgroundColor.SetColor(Color.CornflowerBlue);

The second line has D33 instead of D32 so if D33 is not set yet it would throw that error.