简体   繁体   English

使用jxl API将HashMap打印到Excel

[英]Printing a HashMap to Excel using jxl API

I want to print a HashMap onto an Excel Sheet. 我想将HashMap打印到Excel工作表上。 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. 但是,我无法打印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 . 我只能打印map第一条记录。 ---> ie 1 Hello --->即1个你好

The other records of map are not printed. map的其他记录未打印。

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(); 循环有两个问题:第一个: i应该在外部声明i ,以免每次都将自身重写为2 ;第二个是应该调用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM