使用apache poi将数据导出到excel表格列?

时间:2012-04-07 07:48:02

标签: java excel apache-poi

我设法将数据写入单个列。 我的目的是将数据写入下一个相邻列而不覆盖第一列中的数据。 有什么帮助吗?

InputStream inp;
    try {
        inp = new FileInputStream("D:\\test.xls");
        Workbook wb = WorkbookFactory.create(inp);
        Sheet sheet = wb.getSheetAt(0);
        Row row =  null;

        Cell c = null;

        int rowNum=0;
        Set<String> keySet = new HashSet<String>();
        keySet = tushMap.keySet();
        for (Entry<String, String> entry : tushMap.entrySet()) {
            row=sheet.createRow((short) (sheet.getLastRowNum() + 1));
            System.out.println((short) (sheet.getLastRowNum() + 1));
            c = row.createCell(0);
            c.setCellValue("fff");
            System.out.println("fff");
            System.out.println(entry.getKey() + "/" + entry.getValue());
            rowNum++;
        }


        FileOutputStream fileOut = new FileOutputStream("D:\\test.xls");
        wb.write(fileOut);
        fileOut.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (InvalidFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

这是填充第1列的代码。 填充第二列会覆盖第一列。 请建议一些解决方案.. 提前谢谢。

1 个答案:

答案 0 :(得分:1)

并排获取数据获取循环外的最后一行并将其保存为begening行。保留一个计数器,用于在循环中编辑哪一行。如果该行为null,则创建该行。

rowPos = sheet.getLastRowNum();
for (Entry<String, String> entry : tushMap.entrySet()) {
    rowPos++;
    Row currentRow = sheet.getRow(rowPos);
    if(null == currentRow)
        currentRow = createRow(rowPos);

编辑:

我使用此

获得了令人厌恶的输出
int beginingRow = sheet.getLastRowNum();
            for( int col=0; col<2; col++){
                int currentRow = beginingRow;
                for (int i=0; i<10; i++) {
                    currentRow++;
                    row = sheet.getRow(currentRow);
                    if(null == row)
                        row=sheet.createRow(currentRow);
                    c = row.createCell(col);
                    c.setCellValue("fff");
                    System.out.println("fff");
                    //System.out.println(entry.getKey() + "/" + entry.getValue());
                    rowNum++;
                }
            }

输出

fff fff
fff fff
fff fff
fff fff
fff fff
fff fff
fff fff
fff fff
fff fff
fff fff