I load my sheet with data from a List<T>
using LoadFromCollection
. I then delete some extra columns and then add a Table to the sheet. Finally I save the file.
I expect 2 columns in my table, but there are 4, of which 2 are empty.
I suspect that it may have something to do with the range that I am using, but I can't seem to find the place to adjust the range to not have the 2 columns that was deleted.
Code:
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 Result:
Result:
Try deleting columns after range is loaded in table.
var range = sheet.Cells["A1"].LoadFromCollection(cars, true);
sheet.Tables.Add(range, $"data");
sheet.DeleteColumn(1);
sheet.DeleteColumn(3);