5

我有一个 Excel 文件,它用作我的 Excel 工作的模板,我想以编程方式用数据填充这个模板。

当我创建一行和一个随附的单元格并为新创建的单元格设置边框时,整个工作表都分配有此边框。自然,我只希望单个单元格具有该边框。这是代码:

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;
4

1 回答 1

11

我找到了答案

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;
于 2012-08-21T09:46:16.733 回答