簡體   English   中英

使用jxl API將HashMap打印到Excel

[英]Printing a HashMap to Excel using jxl API

我想將HashMap打印到Excel工作表上。 我正在遍歷地圖並將鍵值提取到標簽中。 但是,我無法打印HashMap的所有字段。 這是我的代碼。

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();
        }
    }
}

我只能打印map第一條記錄。 --->即1個你好

map的其他記錄未打印。

有人可以告訴我為什么嗎?

代碼有什么問題?

循環有兩個問題:第一個: i應該在外部聲明i ,以免每次都將自身重寫為2 ;第二個是應該調用wworkbook.write(); 完成所有單元格添加后僅一次。

以下更改使它可以在我的計算機上運行:

    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