openxml – 插入一行,移动其他

我正在使用openxml来创build一个excel报告。 openxml使用命名范围对模板excel文件进​​行操作。

客户端在行列表的末尾需要一个总计行。 听起来像一个合理的要求!

但是,我从数据库返回的数据表可以包含任意数量的行。 使用模板行和'InsertBeforeSelf',我的总计行被覆盖。

我的问题是,使用openxml,我怎么能插入行到电子表格中,每次插入行时总计行被移动下来?

问候 …

假设你正在使用SDK 2.0,我使用这个函数做了类似的事情:

private static Row CreateRow(Row refRow, SheetData sheetData) { uint rowIndex = refRow.RowIndex.Value; uint newRowIndex; var newRow = (Row)refRow.Clone(); /*IEnumerable<Row> rows = sheetData.Descendants<Row>().Where(r => r.RowIndex.Value >= rowIndex); foreach (Row row in rows) { newRowIndex = System.Convert.ToUInt32(row.RowIndex.Value + 1); foreach (Cell cell in row.Elements<Cell>()) { string cellReference = cell.CellReference.Value; cell.CellReference = new StringValue(cellReference.Replace(row.RowIndex.Value.ToString(), newRowIndex.ToString())); } row.RowIndex = new UInt32Value(newRowIndex); }*/ sheetData.InsertBefore(newRow, refRow); return newRow; } 

我不确定你之前是如何使用InsertBeforeSelf来做的,所以也许这不是一个很大的改进,但是这对我来说是有效的。 我以为你可以使用总计行作为参考行。 (注释掉的部分是因为如果你有你想要维护的引用行后面的行,我做了一些修改,但它主要来自这个线程: http : //social.msdn.microsoft.com/Forums/en- US / oxmlsdk / thread / 65c9ca1c-25d4-482d-8eb3-91a3512bb0ac )

由于它返回新行,因此可以使用该对象来使用数据库中的数据编辑单元格值。 我希望这至less有助于任何人试图做到这一点…

[有多点的人可以把这个文字作为对M_R_H答案的评论]

M_R_H给出的解决scheme对我有所帮助,但却给这个问题带来了新的问题。 如果您按原样使用给定的CreateRow方法,那么如果有任何被移动/重新引用的行具有公式,则CalcChain.xml(在包中)将被打破。 我将下面的代码添加到build议的CreateRow解决scheme。 它仍然不能解决问题,因为我认为这个代码只是修复当前被复制的行引用:

 if (cell.CellFormula != null) { string cellFormula = cell.CellFormula.Text; cell.CellFormula = new CellFormula(cellFormula.Replace(row.RowIndex.Value.ToString(), newRowIndex.ToString())); } 

什么是修正/更新CalcChain.xml的正确方法?

PS:SheetData可以从工作表中获得:

 worksheet.GetFirstChild<SheetData>();