gpt4 book ai didi

java - 使用java将数据的Arraylist写入Excel

转载 作者:行者123 更新时间:2023-12-02 01:50:31 26 4
gpt4 key购买 nike

我想使用java写入包含String ArrayList的数据以实现excel。当我只执行第一个数据时,仅写入 Excel。剩余数据则不会。

public class ExcelGenerator {
public static void main(String args[]) throws FileNotFoundException, HPSFException, IOException, SQLException, NestableException
{
ArrayList<String> arrlist = new ArrayList<String>();
arrlist.add("14");
arrlist.add("7");
arrlist.add("39");
arrlist.add("40");

/* For Loop for iterating ArrayList */
System.out.println("For Loop");
for (int counter = 0; counter < arrlist.size(); counter++) {
System.out.println(arrlist.get(counter));
}


HSSFWorkbook workbook=new HSSFWorkbook();
File f=new File("D:/Test/test.xls");
GeericExcelGenerator gl=new GeericExcelGenerator("Test",workbook);
FileOutputStream outputStream=new FileOutputStream(f);
gl.generate(outputStream,arrlist);

}

public void generate(OutputStream outputStream,ArrayList arrlist) throws SQLException, IOException, NestableException
{
try
{
int currentRow = 0;
for (int counter = 0; counter < arrlist.size(); counter++) {

HSSFRow row = sheet.createRow(currentRow);
System.out.println("Description is"+arrlist.get(counter));

String c=(String) arrlist.get(counter);
int i=0;
HSSFCell cell = HSSFCellUtil.createCell(row, i, null);
cell.setCellValue(c);

i++;
workbook.write(outputStream);
currentRow++;
currentRow++;
}
}catch(IOException e)
{}
finally {
outputStream.close();
}
}
}

最佳答案

尝试以下解决方案可能是由于您的初始化“i”变量

public void generate(OutputStream outputStream, ArrayList arrlist)
throws SQLException, IOException, NestableException {
try {
int currentRow = 0;
int i = 0;
for (int counter = 0; counter < arrlist.size(); counter++) {

HSSFRow row = sheet.createRow(currentRow);
System.out.println("Description is" + arrlist.get(counter));

String c = (String) arrlist.get(counter);

HSSFCell cell = HSSFCellUtil.createCell(row, i, null);
cell.setCellValue(c);

i++;
workbook.write(outputStream);
currentRow++;
currentRow++;

}
} catch (IOException e) {

} finally {
outputStream.close();
}
}

或者您可以使用下面的示例检查您的实现 https://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java

关于java - 使用java将数据的Arraylist写入Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53043353/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com