java数组写入excel_java - 如何使用Java将数组数据写入Excel - 堆栈内存溢出

本文探讨了如何使用Java将字符串数组写入Excel文件,遇到的问题是只有第一个元素被正确写入,而后续元素未显示。通过提供`writeExcel`方法的代码,展示了读取和写入Excel文件的过程,以及可能存在的错误处理。
摘要由CSDN通过智能技术生成

我有一个字符串数组,需要将其插入Excel工作表

我尝试使用下面的代码片段,但是只有第一个值正在插入,而其余的则在控制台中为空。

String[] excelData = {"first", "second", "third", "fourth", "fifth"};

int rowStart = 1;

for (int count = 0; count <= excelData.length; count++) {

writeExcel(fileName, excelData[count], rowStart, 0);

rowStart++;

}

更新

添加了writeExcel代码。

public void writeExcel(String excelFile, String userNumber, int rows, int cols) {

try{

//Create an object of File class to open xlsx file

File file = new File(excelFile);

//Create an object of FileInputStream class to read excel file

FileInputStream inputStream = new FileInputStream(file);

Workbook requestsFile = null;

//Find the file extension by splitting file name in substring and getting only extension name

String fileExtensionName = excelFile.substring(excelFile.indexOf("."));

//Check condition if the file is xlsx file

if(fileExtensionName.equals(".xlsx")){

//If it is xlsx file then create object of XSSFWorkbook class

requestsFile = new XSSFWorkbook(inputStream);

} else if(fileExtensionName.equals(".xls")){

//If it is xls file then create object of XSSFWorkbook class

requestsFile = new HSSFWorkbook(inputStream);

} else {

System.out.println("File format is invalid");

}

//Read excel sheet by sheet name

Sheet sheet = requestsFile.getSheetAt(0);

Cell val1 = sheet.getRow(rows).getCell(cols);

val1.setCellValue(userNumber);

//Close input stream

inputStream.close();

//Create an object of FileOutputStream class to create write data in excel file

FileOutputStream outputStream = new FileOutputStream(file);

//write data in the excel file

requestsFile.write(outputStream);

//close output stream

outputStream.close();

} catch(Exception e){

System.out.println(e.getMessage());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值