【问题标题】:Some columns are not shown in Excel using Apache POI使用 Apache POI 在 Excel 中未显示某些列
【发布时间】:2018-05-20 23:36:34
【问题描述】:

我正在尝试从 java 写到 excel。

From this link here,数据从对象数组中保存。但是,就我而言,数据实际上是从 2 个名为 NameGenerator 的方法中获取的,用于创建一个名称,以及一个名为 PhoneGenerator 的方法来创建一个数字。并将这些值逐列保存到 excel 中。结果如下所示。

彼得 | 5124131

摇滚 | 24141

苏珊 | 067643

但是当前代码会覆盖名称。结果excel文件看起来像

  | 5124131

  | 24141

  | 067643

有人愿意帮助我吗?任何投入将不胜感激!

try {
    
    //create excel
			FileOutputStream fileOut = new FileOutputStream(
					"excelfile.xls");
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet worksheet = workbook.createSheet("Register Data");

			DataGenerator dg = new DataGenerator();

			for (int i = 0; i < 3; i++) {

        //NameGenerator method will create random name
				String name = dg.NameGenerator;
        
        //PhoneGenerator method will create random phone
				String phone = dg.PhoneGenerator;

				worksheet.createRow(i).createCell(0).setCellValue(name);
				worksheet.createRow(i).createCell(1).setCellValue(phone);

			}

      //save excel
			workbook.write(fileOut);
			fileOut.flush();
			fileOut.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

【问题讨论】:

    标签: java excel apache-poi


    【解决方案1】:

    我认为您误用了createRow(index) 方法。您应该为每一行调用一次,否则它将重新创建您之前拥有的内容并且您拥有的所有内容都将丢失(因此您会丢失第一列)。

    这样做:

                ...
                HSSFRow row = worksheet.createRow(i);
                row.createCell(0).setCellValue(name);
                row.createCell(1).setCellValue(phone);
                ...
    

    【讨论】:

    • 很高兴得到了帮助。如果答案解决了您的问题,一般来说,您会接受并投票。 :)
    • 我接受了答案。但是,由于我的声誉低,我不能投票。感谢您重新表述我的问题,以便其他用户更容易理解!
    猜你喜欢
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多