WorkSheet.DeleteColumn不会删除列,只清除数据

时间:2018-06-06 13:25:36

标签: c# excel epplus epplus-4

我使用List<T>LoadFromCollection加载我的工作表。然后我删除一些额外的列,然后在表格中添加一个表格。最后我保存了文件。

我希望我的表中有2列,但有4列,其中2列是空的。

我怀疑它可能与我正在使用的范围有关,但我似乎无法找到调整范围的地方,以便没有删除的2列。

代码:

using OfficeOpenXml;
using System.Collections.Generic;
using System.IO;

namespace DelColCode
{
    class Program
    {
        static void Main(string[] args)
        {
            //get some test data
            var cars = Car.GenerateList();

            var package = new ExcelPackage();

            //Create the worksheet 
            var sheet = package.Workbook.Worksheets.Add("Car List");

            //Read the data into a range
            var range = sheet.Cells["A1"].LoadFromCollection(cars, true);

            //delete the first and last columns
            sheet.DeleteColumn(1);
            sheet.DeleteColumn(3);

            //Make the range a table
            sheet.Tables.Add(range, $"data");

            //save and dispose
            package.File = new FileInfo("carlist.xlsx");
            package.Save();
            package.Dispose();
        }
    }

    public class Car
    {
        public int Id { get; set; }
        public string Make { get; set; }
        public string Model { get; set; }
        public int ReleaseYear { get; set; }


        public Car(int id, string make, string model, int releaseYear)
        {
            Id = Id;
            Make = make;
            Model = model;
            ReleaseYear = releaseYear;
        }

        internal static List<Car> GenerateList()
        {
            return new List<Car>
            {
                //random data
                new Car(1,"Toyota", "Carolla", 1950),
                new Car(2,"Toyota", "Yaris", 2000),
                new Car(3,"Toyota", "Hilux", 1990),
                new Car(4,"Nissan", "Juke", 2010),
                new Car(5,"Nissan", "Trail Blazer", 1995),
                new Car(6,"Nissan", "Micra", 2018),
                new Car(7,"BMW", "M3", 1980),
                new Car(8,"BMW", "X5", 2008),
                new Car(9,"BMW", "M6", 2003),
                new Car(10,"Merc", "S Class", 2001)
            };
        }
    }
}

预期结果:

Expected Results

结果:

Result

2 个答案:

答案 0 :(得分:1)

尝试在表格中加载范围后删除列。

var range = sheet.Cells["A1"].LoadFromCollection(cars, true);
sheet.Tables.Add(range, $"data");
sheet.DeleteColumn(1);
sheet.DeleteColumn(3);

答案 1 :(得分:-1)

使用以下内容:

Excel.Range range = (Excel.Range)sheet.get_Range("C1", Missing.Value);
range.EntireColumn.Delete(Missing.Value);
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);

http://bytes.com/topic/c-sharp/answers/258110-how-do-you-delete-excel-column http://quicktestprofessional.wordpress.com/2008/02/14/delete-columns-from-xl-sheet/