我有一个字符串数组,需要将其插入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());
}
}