使用NPOIdynamic创buildExcel模板

我有一个Excel .xlsx模板文件,我需要dynamic适应我的需要。 它现在只包含标题行,其中两列是“占位符”列,我需要插入新列以适合我的需要。

标题行可能如下所示:

 FirstName | LastName | City | #Modules# | Remarks | #Experts# | Country | Phone 

带有#的两列是“占位符”值 – 取决于从数据库中获得的一些数据,我需要用多列来replace那些单列 – 例如,用三列M1M2M3replace#Modules#并用Expert 1Expert 2取代#Experts#所以最后,我的Excel应该是这样的:

 FirstName | LastName | City | M1 | M2 | M3 | Remarks | Expert 1 | Expert 2 | Country | Phone 

我试图用NPOI v2.2来实现这一目标,但迄今为止还没有取得成功。

方法1:我尝试使用IRow.CreateCell调用,但似乎是覆盖现有的列,所以当我find#Modules#并将其replace为我的实际模块数据,我最终有

 FirstName | LastName | City | M1 | M2 | M3 | Country | Phone 

我的专家占位符已经不存在了(被具体模块之一所覆盖)。

码:

 XSSFWorkbook templateWorkbook = new XSSFWorkbook(templateFileName); ISheet sheet = templateWorkbook.GetSheetAt(0); IRow firstRow = sheet.GetRow(0); // title row // find the #Modules# placeholder - works as expected ICell cellModule = firstRow.Cells.Find(x => x.StringCellValue == "#Modules#"); int moduleIndex = cellModule.ColumnIndex; List<string> listOfModule = new List<string>(new[] { "M1", "M2", "M3" }); foreach (string module in listOfModule) { ICell newCell = firstRow.CreateCell(moduleIndex, CellType.String); newCell.SetCellValue(module); moduleIndex += 1; } 

这将覆盖标题行中的现有单元格,从而“销毁”我的模板文件的一部分…..

方法2:我尝试使用.Insert()方法插入单元格:

 foreach (string module in listOfModule) { // create a new cell, set its value ICell newCell = new XSSFCell(firstRow as XSSFRow, new CT_Cell()); newCell.SetCellValue(module); // insert new cell into title row firstRow.Cells.Insert(moduleIndex, newCell); moduleIndex += 1; } 

但在这种情况下,单元格似乎并没有真正被插入 ,我的标题行根本没有改变,只是保持原来的状态。

有任何想法吗?? NPOI的文件有点……缺乏,至less可以说…..

谢谢!