EPPlus:删除列不起作用

时间:2015-07-27 22:36:24

标签: epplus

我尝试使用EPPlus删除工作表中的列,使用以下解决方案:How to remove a column from excel sheet in epplus

但是,当我运行此单元测试时,第2列中的数据只会被清除。如何完全删除列?

1 个答案:

答案 0 :(得分:4)

多么有趣。似乎在4.0.0中添加了它,然后用4.0.4版打破了它:

http://epplus.codeplex.com/workitem/15310

如果您绝望,可以下载源代码并转到DeleteColumn函数的原始版本(在ExcelWorksheet.cs中)并重新编译:

public void DeleteColumn(int columnFrom, int columns)
{
    lock (this)
    {
        ExcelColumn col = _values.GetValue(0, columnFrom) as ExcelColumn;
        if (col == null)
        {
            var r = 0; 
            var c = columnFrom;
            if(_values.PrevCell(ref r,ref c))
            {
                col = _values.GetValue(0, c) as ExcelColumn;
                if(col._columnMax >= columnFrom)
                {
                    col.ColumnMax=columnFrom-1;
                }
            }
        }

        _values.Delete(1, columnFrom, ExcelPackage.MaxRows, columns);
        _types.Delete(1, columnFrom, ExcelPackage.MaxRows, columns);
        _formulas.Delete(1, columnFrom, ExcelPackage.MaxRows, columns);
        _styles.Delete(1, columnFrom, ExcelPackage.MaxRows, columns);
        _flags.Delete(1, columnFrom, ExcelPackage.MaxRows, columns);
        _commentsStore.Delete(1, columnFrom, ExcelPackage.MaxRows, columns);
        _hyperLinks.Delete(1, columnFrom, ExcelPackage.MaxRows, columns);

        AdjustFormulasColumn(columnFrom, columns);
        FixMergedCellsColumn(columnFrom, columns, true);

        var csec = new CellsStoreEnumerator<object>(_values, 0, columnFrom, 0, ExcelPackage.MaxColumns);

        foreach (var column in csec)    
        {
            if (column is ExcelColumn)
            {
                var c = (ExcelColumn)column;
                if (c._columnMin >= columnFrom)
                {
                    c._columnMin -= columns;
                    c._columnMax -= columns;
                }
            }
        }

        foreach (var tbl in Tables)
        {
            if (columnFrom > tbl.Address.Start.Column && columnFrom <= tbl.Address.End.Column)
            {
                var node = tbl.Columns[0].TopNode.ParentNode;
                var ix = columnFrom - tbl.Address.Start.Column + 1;
                for (int i = 0; i < columns; i++)
                {
                    if (node.ChildNodes.Count > ix)
                    {
                        node.RemoveChild(node.ChildNodes[ix]);
                    }

                } 
                tbl._cols = new ExcelTableColumnCollection(tbl);
            }

            tbl.Address = tbl.Address.DeleteColumn(columnFrom, columns);
        }
    }
}