How would one use importArrayList when you have a 2D ArrayList as ArrayList<ArrayList<String>>
?
Thanks for your query.
There is no specific overload to directly import 2D ArrayList<ArrayList<String>>
but you may workaround it by iterating each ArrayList to import into the worksheet. See the following sample code for your reference.
e.g.
Sample code:
ArrayList<ArrayList<String>> list= new ArrayList<ArrayList<String>>();
ArrayList<String> a = new ArrayList<String>();
ArrayList<String> b = new ArrayList<String>();
a.add("A");
a.add("1A");
a.add("2A");
b.add("AA");
b.add("1AA");
b.add("2AA");
list.add(a);
list.add(b);
Workbook workbook = new Workbook();
// Get the first worksheet (default sheet) in the Workbook
Cells cells = workbook.getWorksheets().get("Sheet1").getCells();
//iterating each array list to import one by one
Iterator<ArrayList<String>> iterator = list.iterator();
int i = 0;
while(iterator.hasNext()){
cells.importArrayList(iterator.next(), i, 0, true);
i = i + cells.getMaxDataRow() +1;
}
// Save the Excel file
workbook.save("f:\\files\\out1.xlsx");
Alternatively, you may convert/save your 2D ArrayList<ArrayList<String>>
into multi-dimensional arrays by using your own code and then try using importArray
method.
@Amjad_Sahi Got an “Invalid row index” error for:
cells.importArrayList(iterator.next(), i, 0, true);
Make sure you have specified valid row index when using the method. If you still could not evaluate it, kindly do share a standalone sample Java (runnable) program/code same as I pasted (above) to reproduce the issue, we will check it soon.
@Amjad_Sahi I couldn’t work out how to fix the above issue so ended up doing what you suggested and converted my ArrayList<ArrayList<String>>
to String[][]
and then simply used cells.importArray
.
It is working nicely now
Alright, and good to know that you have sorted it out by using the other suggested approach.