Delete Row using C# DocumentFormat.OpenXml

I’m using C# DocumentFormat.OpenXml to edit excel file.but have some issues.

Hope everyone can help me to resolved this issues.

I want delete (real or empty) row, but it didn’t work for me。

I’m using sheetData.Elements<Row>() it can’t find empty row.

Have any function can do it Using C# DocumentFormat.OpenXml ?

before

after

I need to delete (Row > Row 93) all Row. Like Picture not only delete cell string. This is my code to delete excel row, but it didn’t work.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>static void DeleteRowsCompletely(string filePath, string sheetName, int startRow, int endRow)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Open(filePath, true))
{
WorkbookPart workbookPart = document.WorkbookPart;
var sheets = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName);
if (!sheets.Any())
{
throw new Exception("Sheet not found.");
}
var sheet = sheets.First();
WorksheetPart worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
for (uint i = (uint)startRow; i <= endRow; i++)
{
var row = sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == i);
if (row != null)
{
if (sheetData.Contains(row))
{
sheetData.RemoveChild(row);
}
}
}
foreach (var row in sheetData.Elements<Row>().Where(r => r.RowIndex.Value > endRow))
{
uint newRowIndex = row.RowIndex.Value - (uint)(endRow - startRow + 1);
row.RowIndex.Value = newRowIndex;
foreach (var cell in row.Elements<Cell>())
{
string oldCellReference = cell.CellReference.Value;
cell.CellReference = new StringValue(UpdateCellReference(oldCellReference, newRowIndex));
}
}
worksheetPart.Worksheet.Save();
}
}
static string UpdateCellReference(string cellReference, uint newRowIndex)
{
string columnPart = new string(cellReference.Where(char.IsLetter).ToArray());
return $"{columnPart}{newRowIndex}";
}
</code>
<code>static void DeleteRowsCompletely(string filePath, string sheetName, int startRow, int endRow) { using (SpreadsheetDocument document = SpreadsheetDocument.Open(filePath, true)) { WorkbookPart workbookPart = document.WorkbookPart; var sheets = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName); if (!sheets.Any()) { throw new Exception("Sheet not found."); } var sheet = sheets.First(); WorksheetPart worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id); var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>(); for (uint i = (uint)startRow; i <= endRow; i++) { var row = sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == i); if (row != null) { if (sheetData.Contains(row)) { sheetData.RemoveChild(row); } } } foreach (var row in sheetData.Elements<Row>().Where(r => r.RowIndex.Value > endRow)) { uint newRowIndex = row.RowIndex.Value - (uint)(endRow - startRow + 1); row.RowIndex.Value = newRowIndex; foreach (var cell in row.Elements<Cell>()) { string oldCellReference = cell.CellReference.Value; cell.CellReference = new StringValue(UpdateCellReference(oldCellReference, newRowIndex)); } } worksheetPart.Worksheet.Save(); } } static string UpdateCellReference(string cellReference, uint newRowIndex) { string columnPart = new string(cellReference.Where(char.IsLetter).ToArray()); return $"{columnPart}{newRowIndex}"; } </code>
static void DeleteRowsCompletely(string filePath, string sheetName, int startRow, int endRow)
    {
        using (SpreadsheetDocument document = SpreadsheetDocument.Open(filePath, true))
        {
            WorkbookPart workbookPart = document.WorkbookPart;
            var sheets = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName);
            if (!sheets.Any())
            {
                throw new Exception("Sheet not found.");
            }

            var sheet = sheets.First();
            WorksheetPart worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
            var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

            for (uint i = (uint)startRow; i <= endRow; i++)
            {
                var row = sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == i);

                if (row != null)
                {
                    if (sheetData.Contains(row))
                    {
                        sheetData.RemoveChild(row);
                    }
                }
            }

            foreach (var row in sheetData.Elements<Row>().Where(r => r.RowIndex.Value > endRow))
            {
                uint newRowIndex = row.RowIndex.Value - (uint)(endRow - startRow + 1);
                row.RowIndex.Value = newRowIndex;

                foreach (var cell in row.Elements<Cell>())
                {
                    string oldCellReference = cell.CellReference.Value;
                    cell.CellReference = new StringValue(UpdateCellReference(oldCellReference, newRowIndex));
                }
            }

            worksheetPart.Worksheet.Save();
        }
    }

    static string UpdateCellReference(string cellReference, uint newRowIndex)
    {
        string columnPart = new string(cellReference.Where(char.IsLetter).ToArray());
        return $"{columnPart}{newRowIndex}";
    }

6

I tried to hide the extra empty rows. Just like what we discussed, the row count in my file is 5 so that I can’t remove rows which index is more than 10. Then I have a workaround to hide the rows and the test result is like below.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
var rowcounts = sheetData.Elements<Row>().Count();
var rowsToRemove = sheetData.Elements<Row>()
.Where(row => row.RowIndex > 10)
.ToList();
// Remove empty rows
foreach (var row in rowsToRemove)
{
sheetData.RemoveChild(row);
}
for (uint rowIndex = 10; rowIndex <= 1048576; rowIndex++) // Excel has 1048576 rows in total
{
Row row = new Row() { RowIndex = rowIndex, Hidden = true };
sheetData.Append(row); // Add hidden rows
}
worksheetPart.Worksheet.Save();
</code>
<code>WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart; WorksheetPart worksheetPart = workbookPart.WorksheetParts.First(); SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>(); var rowcounts = sheetData.Elements<Row>().Count(); var rowsToRemove = sheetData.Elements<Row>() .Where(row => row.RowIndex > 10) .ToList(); // Remove empty rows foreach (var row in rowsToRemove) { sheetData.RemoveChild(row); } for (uint rowIndex = 10; rowIndex <= 1048576; rowIndex++) // Excel has 1048576 rows in total { Row row = new Row() { RowIndex = rowIndex, Hidden = true }; sheetData.Append(row); // Add hidden rows } worksheetPart.Worksheet.Save(); </code>
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

var rowcounts = sheetData.Elements<Row>().Count();
var rowsToRemove = sheetData.Elements<Row>()
                    .Where(row => row.RowIndex > 10)
                    .ToList();
// Remove empty rows
foreach (var row in rowsToRemove)
{
    sheetData.RemoveChild(row);
}

for (uint rowIndex = 10; rowIndex <= 1048576; rowIndex++) // Excel has 1048576 rows in total
{
    Row row = new Row() { RowIndex = rowIndex, Hidden = true };
    sheetData.Append(row); // Add hidden rows
}

worksheetPart.Worksheet.Save();

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật