Search code examples
export-to-excelnpoi

Border for created cell with npoi


I have an Excel File which serves as a template for my Excel work and I want to programatically fill this template with data.

When I create a row and an accompanying cell and set a border for the newly created cell, the whole sheet is assigned this border. Naturally, I only want the single cell to have that border. Here is the code:

string path = Application.StartupPath + "\\" + "Excels\\myTemplate.xls";
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);

HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);
HSSFSheet sheet = templateWorkbook.GetSheet("sheet2");

int rowIndex = 3;
var row = sheet.CreateRow(rowIndex);

int i = 0;
string zoneNo;
string SubsidiaryCode = string.Empty;
foreach (DataRow r in dtBill.Rows)
{
  SubsidiaryCode = (r["SubsidiaryCode"].ToString().Trim());
  zoneNo = (r["ZoneNO"].ToString().Trim());

  HSSFCell cell = (HSSFCell)row.CreateCell(i);
  cell.SetCellValue("Zone " + zoneNo + "-code :" + SubsidiaryCode);
  cell.CellStyle.BorderBottom = HSSFCellStyle.BORDER_MEDIUM;
  i++;

  row.CreateCell(i).SetCellValue(r["Date"].ToString().Trim());
  row.CreateCell(i).CellStyle.BorderBottom = HSSFCellStyle.BORDER_MEDIUM;
  i++;

  rowIndex++;
  row = sheet.CreateRow(rowIndex);
  i = 0;
}

sheet.ForceFormulaRecalculation = true;

Solution

  • I found the answer

    var row = sheet.CreateRow(rowGlobal);
    
    
    HSSFCellStyle style1 = templateWorkbook.CreateCellStyle();
            style1.BorderRight = HSSFCellStyle.BORDER_MEDIUM;
            style1.BorderBottom = HSSFCellStyle.BORDER_MEDIUM;
            style1.Alignment = HSSFCellStyle.ALIGN_CENTER;
            //style1.FillPattern = HSSFCellStyle.SOLID_FOREGROUND;
            //style1.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.GREEN.index;
            HSSFFont font1 = templateWorkbook.CreateFont();
            //font1.Color = NPOI.HSSF.Util.HSSFColor.BROWN.index;
            font1.FontName = "B Nazanin";
            style1.SetFont(font1);
    
    cell = row.CreateCell(2);
               cell.SetCellValue(0);
               cell.CellStyle = style1;