只有最后一个索引值被插入到Excel表格
我想通过网络表格将数据写入excel。
开始的行使用空白数据创建,最后一行填充数据,最后一个索引值。
即使数据存在于Arraylist
中,其他行也没有被填充数据。只有最后一个索引值被插入到Excel表格
public class Write_Excel { public static `FileInputStream` `fis`;
public static FileOutputStream fos;
public static `HSSFWorkbook` `wb`;
public static `HSSFSheet` `sheet`;
public static `HSSFCell` `cell`;
public static `HSSFRow` `row`;
public static `int a = 0`;
public static void write_Excel(String fileName, String sheetName,
`ArrayList`<String> `dataToWrite`) throws `IOException` {
fos = new `FileOutputStream(fileName);
wb = new HSSFWorkbook();
sheet = `wb.createSheet(sheetName);`
`row = sheet.createRow(a++);`
for (int i = 0; i < 16; i++) {
cell = row.createCell(i);
System.out.println(dataToWrite.get(i).toString());
cell.setCellValue(new HSSFRichTextString(dataToWrite.get(i)));
}
wb.write(fos);
fos.flush();
}
}
回答:
当你这样做,你需要创建一个新的工作簿每次调用的函数,你刚刚结束抹去以前的。因此你只能得到最后一次通话的结果。
如果您想在每次调用时添加一行,请按照这种方式进行,您需要将行号和工作簿作为类变量。此外,您需要掌握已经创建的工作表以追加到工作表。或者你也会抹去它。
public static void main(String[] args) { try {
write_Excel("myFile.xls","sheetName",
Arrays.asList("value 1", "value 2", "value 3"));
write_Excel("myFile.xls","sheetName",
Arrays.asList("value 4", "value 5", "value 6"));
} catch(IOException e) {
e.printStackTrace();
}
}
private static int newRowIndex = 0;
private static HSSFWorkbook workbook = new HSSFWorkbook();
public static void write_Excel(String fileName, String sheetName, List<String> dataToWrite) throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
// open or create sheet
HSSFSheet sheet = workbook.getSheet(sheetName) != null ?
workbook.getSheet(sheetName) :
workbook.createSheet(sheetName);
// create a new row
HSSFRow row = sheet.createRow(newRowIndex ++);
// write your data in the new row
for (int colIndex = 0; colIndex < dataToWrite.size(); colIndex++) {
HSSFCell cell = row.createCell(colIndex);
cell.setCellValue(new HSSFRichTextString(dataToWrite.get(colIndex)));
}
workbook.write(fos);
fos.flush();
fos.close();
}
回答:
你应该加入这一行成环
HSSFRow row = sheet.createRow(a++);
以上是 只有最后一个索引值被插入到Excel表格 的全部内容, 来源链接: utcz.com/qa/262732.html