#region 2.NPOI读取Excel 验证Excel数据的有效性(非空) 并修改指定单元格样式
IWorkbook workbook = null;
ISheet sheet = null;
ArrayList questionRowIndex = new ArrayList();/*收集出现问题行的索引*/
using (FileStream fs = System.IO.File.Open(readExcelPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
#region 选择解析方式
if (dataLog.ExcelName.IndexOf(“.xlsx”) > 0)
{
workbook = new XSSFWorkbook(fs);
}
else if(dataLog.ExcelName.IndexOf(“.xls”) > 0)
{
workbook = new HSSFWorkbook(fs);
}
#endregion
#region 核验数值列数据是否为空 并记录为空索引行 修改Excel指定索引行后重新保存
sheet = workbook.GetSheetAt(0);/*指定数据格式只读取索引值为0的第一个sheet*/
IRow row = null;
for(int j =1;j < sheet.PhysicalNumberOfRows && sheet.GetRow(j) != null;j++)/*j=1 从索引的第一行开始过滤掉表头*/
{
row = sheet.GetRow(j);
if (string.IsNullOrWhiteSpace(row.GetCell(5).ToString()))/*验证数值非空*/
{
questionRowIndex.Add(j);
/*修改样式关键代码*/
ICellStyle style = workbook.CreateCellStyle();
style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index;
style.FillPattern = FillPattern.SolidForeground;
style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index;
/*修改指定单元格样式 如果要修改行样式则需要将row.Cells.Count循环出来,挨个设置!*/
row.Cells[5].CellStyle = style;
//for(int i=0;i<row.Cells.Count;i++)
//{
// row.Cells[i].CellStyle = style;
//}
/*重新修改文件指定单元格样式*/
FileStream fs1 = System.IO.File.OpenWrite(readExcelPath);
workbook.Write(fs1);
fs1.Close();
}
}
#endregion
}