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

该篇博客讲述了作者遇到将字符串数组写入Excel的问题,代码仅能插入第一个元素,后续元素失效。通过分析提供的`writeExcel`方法,我们揭示了问题并提供可能的解决方案,涉及XSSFWorkbook和HSSFWorkbook的选择及数据写入细节。

我有一个字符串数组,需要将其插入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、付费专栏及课程。

余额充值