如何使用Open Office XML SDK从Excel文件中删除行 [英] How can I delete a row from an excel file using Open Office XML SDK

查看:372
本文介绍了如何使用Open Office XML SDK从Excel文件中删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码,使用OOXML从excel电子表格中删除一行。我可以删除行数据,但行仍然作为空行存在。请帮我完全删除excel文件中的行。

I have written the below code to delete a row from an excel spreadsheet using OOXML . I can able to remove the row data , however the row still existing as a blank row. Please help me to completely remove the row from the excel file.

public static void DeleteRowFromExcel(string docName, string sheetName, uint rowIndex)
    {
        // Open the document for editing.
        using (SpreadsheetDocument document = SpreadsheetDocument.Open(docName, true))
        {
            IEnumerable<sheet> sheets = document.WorkbookPart.Workbook.GetFirstChild<sheets>().Elements<sheet>().Where(s => s.Name == sheetName);
            if (sheets.Count() == 0)
            {
                // The specified worksheet does not exist.
                return;
            }
            string relationshipId = sheets.First().Id.Value;
            WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId);
            Row row=GetRow(worksheetPart,rowIndex);
            row.RemoveAllChildren();
            worksheetPart.Worksheet.Save();                
        }

    }</sheet></sheets></sheet>

推荐答案

对不起我的英文,但我得到了下一个问题的结果:

1)当我逐行删除一行时,删除(),然后对于以下所有行,我将RowIndex属性更改为RowIndex.Value - = 1;

2)对于所有单元格在以下所有行中,我还通过减少-1来更改CellReference属性。 CellReference属性存储为Excel单元格地址。



例如,如果我需要在Excel工作表中删除第四行,那么对于row.RowIndex.Value = 4我调用行。去掉()。对于row.RowIndex.Value = 5的下一行,我将RowIndex.Value设置为4,并且所有单元格都将CellReference.Value更改为'A5' - > 'A4','B5' - > 'B4'等等。
Sorry for my English, but I get result for this problem as next:
1) When I delete one row by row.Remove(), then for all the following rows I change RowIndex property to RowIndex.Value -= 1;
2) For all cells of all following rows I also change CellReference property by decrease it on -1. CellReference property stored as like Excel cell address.

For example, if I need delete fourth row in excel sheet, so for row.RowIndex.Value = 4 I call row.Remove(). For next row with row.RowIndex.Value = 5, I set RowIndex.Value to 4 and for all it cells change CellReference.Value like 'A5' -> 'A4', 'B5' -> 'B4' and so on.


这篇关于如何使用Open Office XML SDK从Excel文件中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆