博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Excel文件上传,高亮错误的行和列

Posted on 2017-04-02 00:52  奋斗ITan_yxing  阅读(512)  评论(0编辑  收藏  举报
/// <summary>
        /// Excel模板写入错误信息
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="errorAllList"></param>
        public void ErrorWriteExcel(string fileName, List<RowCellSheetMessage> errorAllList)
        {
            FileStream fs = System.IO.File.Open(fileName, FileMode.Open, FileAccess.ReadWrite);
            IWorkbook workbook = WorkbookFactory.Create(fs);
            fs.Dispose();

            ICellStyle rowCellStyle = workbook.CreateCellStyle();
            rowCellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
            rowCellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
            rowCellStyle.FillPattern = FillPattern.SolidForeground;
            rowCellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Pink.Index;

            ICellStyle cellStyle = workbook.CreateCellStyle();
            cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
            cellStyle.FillPattern = FillPattern.SolidForeground;
            cellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Pink.Index;

            for (int i = 0; i < workbook.NumberOfSheets; i++)
            {
                ISheet sheet = workbook.GetSheetAt(i);
                IRow headerRow = sheet.GetRow(0);
                if (!errorAllList.Exists(l => l.SheetName.Contains(sheet.SheetName)))
                {
                    continue;
                }

                List<RowCellSheetMessage> currentErrorList = errorAllList.Where(l => l.SheetName == sheet.SheetName).ToList();
                for (int j = 0; j < sheet.PhysicalNumberOfRows; j++)
                {
                    //获取Excel行
                    IRow row = sheet.GetRow(j);
                    if (row == null)
                    {
                        row = sheet.CreateRow(j); ;
                    }

                    for (int r = 0; r < headerRow.PhysicalNumberOfCells; r++)
                    {
                        ICell cell = row.GetCell(r);
                        if (cell == null)
                        {
                            cell = row.CreateCell(r);
                            cell.SetCellValue("");
                        }

                        if (currentErrorList.Select(l => l.RowNum).Contains(j))
                        {
                            cell.CellStyle = rowCellStyle;
                        }
                    }
                }

                //获取Excel列
                foreach (var item in currentErrorList)
                {
                    ICell cell = sheet.GetRow(item.RowNum).GetCell(item.CellNum);

                    IDrawing patr = sheet.CreateDrawingPatriarch();
                    IComment comment = patr.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, 3, 3, 8, 8));
                    comment.String = new HSSFRichTextString(item.Message);
                    cell.CellComment = comment;

                    cell.CellStyle = cellStyle;
                }
            }

            // 创建错误Sheet
            if (errorAllList.Count > 0)
            {
                var errorDictionary = errorAllList
                                        .GroupBy(l => new { l.SheetName, l.RowNum })
                                        .Select(l => new { Key = l.Key, Value = l })
                                        .ToDictionary(l => l.Key, v => v.Value);
                int maxErrorCount = errorDictionary.Values.Max(l => l.Count());

                #region 设置错误Sheet的标题行
                ISheet errorSheet = workbook.CreateSheet("错误说明");
                IRow errorRow = errorSheet.CreateRow(0);
                ICell errorCell1 = errorRow.CreateCell(0, CellType.String);
                errorCell1.SetCellValue("Sheet名称");
                ICell errorCell2 = errorRow.CreateCell(1, CellType.String);
                errorCell2.SetCellValue("Excel行号");
                for (int i = 0; i < maxErrorCount; i++)
                {
                    ICell errorCell3 = errorRow.CreateCell(i + 2, CellType.String);
                    errorCell3.SetCellValue("错误说明" + (i + 1));
                    errorSheet.SetColumnWidth(i + 2, 20 * 256);
                }
                errorSheet.SetColumnWidth(0, 20 * 256);
                errorSheet.SetColumnWidth(1, 10 * 256);
                #endregion

                #region 设置错误行标题的样式
                errorRow.HeightInPoints = 20;

                ICellStyle errorStyle = workbook.CreateCellStyle();
                errorStyle.BorderBottom = BorderStyle.Thin;
                errorStyle.BorderTop = BorderStyle.Thin;
                errorStyle.BorderLeft = BorderStyle.Thin;
                errorStyle.BorderRight = BorderStyle.Thin;
                errorStyle.Alignment = HorizontalAlignment.Center;
                errorStyle.VerticalAlignment = VerticalAlignment.Center;
                errorStyle.FillForegroundColor = HSSFColor.LightYellow.Index;
                errorStyle.FillPattern = FillPattern.SolidForeground;

                IFont errorFont = workbook.CreateFont();
                errorFont.Color = HSSFColor.Red.Index;
                errorFont.FontHeightInPoints = 9;
                errorStyle.SetFont(errorFont);

                for (int i = 0; i < errorRow.PhysicalNumberOfCells; i++)
                {
                    ICell errorCell = errorRow.GetCell(i);
                    errorCell.CellStyle = errorStyle;
                }
                #endregion

                #region 为错误Sheet赋值
                int error_Row_Index = 0;
                foreach (var item in errorDictionary)
                {
                    error_Row_Index++;
                    errorRow = errorSheet.CreateRow(error_Row_Index);

                    errorCell1 = errorRow.CreateCell(0, CellType.String);
                    errorCell1.SetCellValue(item.Key.SheetName);
                    errorCell2 = errorRow.CreateCell(1, CellType.String);
                    errorCell2.SetCellValue(item.Key.RowNum);

                    List<RowCellSheetMessage> currentRowErrorList = item.Value.ToList();
                    int error_Cell_Index = 1;
                    foreach (var errorItem in currentRowErrorList)
                    {
                        error_Cell_Index++;
                        ICell errorCell3 = errorRow.CreateCell(error_Cell_Index, CellType.String);
                        errorCell3.SetCellValue(errorItem.Message);
                    }

                    errorStyle = workbook.CreateCellStyle();
                    errorStyle.BorderBottom = BorderStyle.Thin;
                    errorStyle.BorderTop = BorderStyle.Thin;
                    errorStyle.BorderLeft = BorderStyle.Thin;
                    errorStyle.BorderRight = BorderStyle.Thin;
                    errorStyle.Alignment = HorizontalAlignment.Center;
                    errorStyle.VerticalAlignment = VerticalAlignment.Center;
                    errorFont = workbook.CreateFont();
                    errorFont.FontHeightInPoints = 9;
                    errorStyle.SetFont(errorFont);

                    for (int i = 0; i < errorRow.PhysicalNumberOfCells; i++)
                    {
                        ICell errorCell = errorRow.GetCell(i);
                        errorCell.CellStyle = errorStyle;
                    }
                }
                #endregion
            }

            using (FileStream fsWrite = File.OpenWrite(fileName))
            {
                workbook.Write(fsWrite);
            }

            workbook = null;
        }

  

[Serializable]
    public class RowCellSheetMessage
    {
        /// <summary>
        /// Excel行号 从下标0开始
        /// </summary>
        public int RowNum { get; set; }

        /// <summary>
        /// Excel列号 从下标0开始
        /// </summary>
        public int CellNum { get; set; }

        /// <summary>
        /// Sheet名称
        /// </summary>
        public string SheetName { get; set; }

        /// <summary>
        /// 错误信息
        /// </summary>
        public string Message { get; set; }
    }

  效果图: