Android Studio中如何通过循环给Excel单元格写入动态变化的数值
问题根因
循环未执行的核心原因是for循环的终止条件逻辑错误:原有代码中for(int i3 = 1; i3==j+1 ; i3++)的判断规则是只有i3等于j+1时才会进入循环,而i3初始值为1,只要j+1≠1,循环一次都不会运行。
其他无效/风险代码
- 循环内
sheet.getWritableCell(text)是无效代码:该方法入参要求为「列号, 行号」,传入字符串无任何作用,直接删除即可 - 硬编码依赖变量
j作为循环边界容易触发数组越界,建议直接用xCor数组的长度作为循环终止条件 - 后续的
sheet.addCell(label7)会覆盖循环中写入的第1行第2列的内容,如非必要可以删除
修正后代码
String sdCard = getExternalFilesDir("/").getAbsolutePath(); File directory = new File(sdCard + "/MyFolder/"); // 目录不存在则创建 if(!directory.isDirectory()){ directory.mkdirs(); } File file = new File(directory, fileName); WorkbookSettings wbSettings = new WorkbookSettings(); WritableWorkbook workbook; try { workbook = Workbook.createWorkbook(file, wbSettings); WritableSheet sheet = workbook.createSheet("Mydata1", 0); // 写入表头 Label label0 = new Label(0,0,"Date"); Label label1 = new Label(1,0,"time"); Label label2 = new Label(2,0,"xCor"); Label label3 = new Label(3,0,"score"); try { sheet.addCell(label0); sheet.addCell(label1); sheet.addCell(label2); sheet.addCell(label3); // 修正循环条件:从第1行开始写入,直到xCor数组遍历完成 for(int i3 = 1; i3 < xCor.length; i3++) { String text = xCor[i3]; Label label4 = new Label(2,i3,text); Label label5 = new Label(1,i3,text); sheet.addCell(label4); sheet.addCell(label5); } // 如确实需要单独写入xCor[2]到第1行第2列,保留下方两行即可,会覆盖循环写入的内容 // Label label7 = new Label(2,1,xCor[2]); // sheet.addCell(label7); } catch (RowsExceededException | WriteException e) { e.printStackTrace(); } workbook.write(); try { workbook.close(); } catch (WriteException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); }
如果你确实需要循环到j的位置,将循环条件改为i3 <= j即可。
内容的提问来源于stack exchange,提问作者sara 10
相关产品推荐
相关产品推荐

