日期:2014-05-17  浏览次数:21265 次

怎么给EXCEL一个区域的单元格加边框
C# code
Range ra1;
ra1=sheet.get_Range(excel.Cells[1, 1], excel.Cells[5, 3]);
ra1.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());
ra1 = null;



我这个的结果就是这个区域所有的单元格外面有一个大的边框
我希望那种 所有边框的效果 就是每个单元格都有边框

应该怎么写
还有 关闭这个对象的命令我用
C# code
ra1 = null;
对吗

------解决方案--------------------
可以使用NPOI库,下面是我用NOPI库导出数据的格式。


该库使用也比较简单
C# code
private void InitWorksheet(Sheet sheetUser)
        {
            //创建结构
            CreateHeaderForSheet(sheetUser);

            //设置列宽
            sheetUser.SetColumnWidth(0, 10 * 256);
            sheetUser.SetColumnWidth(1, 50 * 256);
            sheetUser.SetColumnWidth(2, 10 * 256);
            sheetUser.SetColumnWidth(3, 20 * 256);
            //冻结行
            sheetUser.CreateFreezePane(0, 1);
        }

        /// <summary>
        /// 创建结构
        /// </summary>
        /// <param name="sheet"></param>
        private void CreateHeaderForSheet(Sheet sheet)
        {
            const int rowHeaderIndex = 0;
            Row row = sheet.CreateRow(rowHeaderIndex);

            Cell cell1 = row.CreateCell(0);
            cell1.SetCellValue("机构编号");
            Cell cell2 = row.CreateCell(1);
            cell2.SetCellValue("机构名称");
            Cell cell3 = row.CreateCell(2);
            cell3.SetCellValue("用户名");
            Cell cell4 = row.CreateCell(3);
            cell4.SetCellValue("密码");

            //- 加粗,白色前景色
            var cellFont = sheet.Workbook.CreateFont();
            cellFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
            cellFont.FontHeight = 200;
            cellFont.Color = NPOI.HSSF.Util.HSSFColor.WHITE.index;

            var cellStyle = sheet.Workbook.CreateCellStyle();
            cellStyle.FillPattern = FillPatternType.SOLID_FOREGROUND;
            cellStyle.FillForegroundColor = HSSFColor.LIGHT_ORANGE.index;
            cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.CENTER;
            cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
            cellStyle.BorderBottom = CellBorderType.THIN;
            cellStyle.BorderLeft = CellBorderType.THIN;
            cellStyle.BorderRight = CellBorderType.THIN;
            cellStyle.BorderTop = CellBorderType.THIN;

            cellStyle.SetFont(cellFont);


            cell1.CellStyle = cellStyle;
            cell2.CellStyle = cellStyle;
            cell3.CellStyle = cellStyle;
            cell4.CellStyle = cellStyle;
        }