你不會喜歡這個......問題是你的模板中有第9和第11行。您必須正確設置它們,因爲它們的RowIndex必須更新,並且Row元素的子元素Cell元素必須具有其CellReference屬性(以及CellFormula,如果有的話)更正。
假設您有6個新項目。然後第9行變爲第15行。「舊」行9中的單元格A9必須更新爲A15。我已經給出了更新RowIndex和CellReference的代碼,但它不是萬無一失的。您已被警告。
另請注意,我已將起始索引從9更改爲8.這是因爲在執行InsertAfter()之前,代碼先增加(newRowIndex ++)。哦,你會發現它...
此外,我更新第11行之前第9行,因爲我害怕碰撞。如果您有兩個新項目,並且您首先更新第9行,則它將成爲第11行。然後您將有兩排第11行。那麼原來的第11行是哪個?在這些情況下,當增加行索引時,從具有較高RowIndex的行開始。
using (var spreadSheet = SpreadsheetDocument.Open(memoryStream, true, openSettings))
{
var worksheet = GetWorksheet(spreadSheet);
var worksheetPart = worksheet.WorksheetPart;
var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
Row currentRow;
Row cloneRow;
Cell currentCell;
Cell cloneCell;
// Replace for rows 11 and 9, because they exist after your inserted rows
currentRow = sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == 11);
cloneRow = (Row)currentRow.CloneNode(true);
cloneRow.RowIndex += (uint)Items.Count;
foreach (var child in cloneRow.ChildElements)
{
if (child is Cell)
{
currentCell = (Cell)child;
cloneCell = (Cell)currentCell.CloneNode(true);
// IMPORTANT! this is a very simplistic way of replace something like
// A11 to A16 (assuming you have 5 rows to insert)
// A more robust way of replacing is beyond this solution's scope.
cloneCell.CellReference = cloneCell.CellReference.Value.Replace("11", cloneRow.RowIndex);
cloneRow.ReplaceChild<Cell>(cloneCell, currentCell);
}
}
sheetData.ReplaceChild<Row>(cloneRow, currentRow);
currentRow = sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == 9);
cloneRow = (Row)currentRow.CloneNode(true);
cloneRow.RowIndex += (uint)Items.Count;
foreach (var child in cloneRow.ChildElements)
{
if (child is Cell)
{
currentCell = (Cell)child;
cloneCell = (Cell)currentCell.CloneNode(true);
cloneCell.CellReference = cloneCell.CellReference.Value.Replace("9", cloneRow.RowIndex);
cloneRow.ReplaceChild<Cell>(cloneCell, currentCell);
}
}
sheetData.ReplaceChild<Row>(cloneRow, currentRow);
var newRowIndex = 8;
foreach (var item in Items)
{
newRowIndex++;
var newRow = new Row()
{
RowIndex = (uint)newRowIndex
};
var lastRow = sheetData.Elements<Row>().LastOrDefault(l => l.RowIndex == newRowIndex - 1);
sheetData.InsertAfter(newRow, lastRow);
}
worksheet.Save();
}
檢查此鏈接 http://stackoverflow.com/questions/12657611/how-to-add-a-row-to-excel-using -openxml-sdk-2-0?rq = 1 – Veer 2013-04-29 12:24:14
** Veer B. Singh **,我沒有問題插入行,並且您對任何問題的評論!!!我的問題在插入行之前最後一行並且最後更改行索引... – Elyor 2013-04-29 12:36:32