I want to print a HashMap onto an Excel Sheet. I am iterating through the map and extracting the key, value into a label. However, I am unable to print all the fields of the HashMap. Here's my code.
import java.io.File;
import java.util.HashMap;
import java.util.Map.Entry;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
class WriteExcel {
HashMap<Integer, String> map = new HashMap<Integer, String>();
public void writeToFile() throws Exception {
WritableWorkbook wworkbook = Workbook.createWorkbook(new File("D:\\output.xls"));
WritableSheet wsheet = wworkbook.createSheet("First Sheet", 0);
Label l1 = new Label(0, 0, "Serial No");
Label l2 = new Label(1, 0, "Name");
wsheet.addCell(l1);
wsheet.addCell(l2);
map.put(1, "Hello");
map.put(2, "World");
map.put(3, "StackOverflow");
map.put(4, "StackExchange");
for (Entry<Integer, String> entry : map.entrySet()) {
int i = 2;
Label lbl1 = new Label(0, i, entry.getKey().toString());
Label lbl2 = new Label(1, i, entry.getValue());
i++;
wsheet.addCell(lbl1);
wsheet.addCell(lbl2);
wworkbook.write();
}
wworkbook.write();
wworkbook.close();
}
}
public class Test2 {
public static void main(String[] args)
{
WriteExcel write = new WriteExcel();
try {
write.writeToFile();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am able to print only first record of map
. ---> i.e. 1 Hello
The other records of map
are not printed.
Could someone tell why is that so.?
What's wrong in the code.?
There are two problems with the loop: the first: i
should be declared outside in order not to override itself to 2
every time, and the second is that you should call wworkbook.write();
only once after you're done adding all the cells.
The following change made it work on my computer:
int i = 2;
for (Entry<Integer, String> entry : map.entrySet()) {
Label lbl1 = new Label(0, i, entry.getKey().toString());
Label lbl2 = new Label(1, i, entry.getValue());
i++;
wsheet.addCell(lbl1);
wsheet.addCell(lbl2);
}
wworkbook.write();
wworkbook.close();