Is there any method for getting multiple distinct columns from EPPlus in c# than this:
range = sheet.Cells["A:B,E:F"];
Update: I would like to programmatically step through the columns based on other variables like List<int[]> Columns = {[1,2],[5,6]}
, rather than using hard-coded letters. I keep trying to make range.TakeColumns() work, but can't get there.
You can do something like this:
using OfficeOpenXml;
namespace Test
{
public partial class Program
{
public static void Main ()
{
FileInfo existingFile = new FileInfo ("01.xlsx");
ExcelPackage package = new ExcelPackage (existingFile);
ExcelWorksheet sheet = package.Workbook.Worksheets [0];
var columnPairs = new List<int[]> () {
new int[] { 1, 2 },
new int[] { 4, 6 }
};
foreach (var pair in columnPairs)
{
// Get the ExcelRangeColumn delimited by this pair of columns
var rangeColumn = sheet.Columns [pair[0], pair[1]];
Console.WriteLine (rangeColumn.StartColumn.ToString() + " - " + rangeColumn.EndColumn.ToString());
// Get the associated ExcelRangeBase and browse all cells
foreach (var cell in rangeColumn.Range)
Console.WriteLine (cell + ": " + cell.Value);
}
}
}
}
I'm printing the name and the value of each cell in each column range (for a sample sheet with 6 columns x 3 rows):
1 - 2
A1: 1
B1: 100
A2: 2
B2: 200
A3: 3
B3: 300
4 - 6
D1: -1
E1: -100
F1: -10
D2: -2
E2: -200
F2: -20
D3: -3
E3: -300
F3: -30