首页 > 解决方案 > 如何在单元格中设置值以在 Android Studio 中编写

问题描述

我设法为我的 Excel 设置标签,但我想为作为数组的单元格设置值,我想用 For 循环设置值,但是使用此代码,我的 for 循环不起作用,标签 4 和 5 不写在我的 Excel 文件中。如何将值设置为这些值在每次迭代中都会发生变化的单元格?

String sdCard = getExternalFilesDir("/").getAbsolutePath();
File directory = new File(sdCard + "/MyFolder/");

//create directory if not exist
if(!directory.isDirectory()){
    directory.mkdirs();
    //Toast.makeText(getApplicationContext(),"dir",Toast.LENGTH_LONG).show();
}
//file path
File file = new File(directory, fileName);
WorkbookSettings wbSettings = new WorkbookSettings();
//wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook;
try {
    int a = 1;
    workbook = Workbook.createWorkbook(file, wbSettings);
    //Toast.makeText(getApplicationContext(),"done4",Toast.LENGTH_LONG).show();
    //Excel sheet name. 0 represents first sheet
    WritableSheet sheet = workbook.createSheet("Mydata1", 0);
    //Toast.makeText(getApplicationContext(),"done3",Toast.LENGTH_LONG).show();

    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");
    Label label7 = new Label(2,1,xCor[2]);


    try {
        sheet.addCell(label0);
        sheet.addCell(label1);
        sheet.addCell(label2);
        sheet.addCell(label3);

        for(int i3 = 1; i3==j+1 ; i3++) {
            String text = xCor[i3];
            sheet.getWritableCell(text);
            Label label4 = new Label(2,i3,text);
            Label label5 = new Label(1,i3,text);
            sheet.addCell(label4);
            sheet.addCell(label5);
        }


        sheet.addCell(label7);
    } catch (RowsExceededException e) {
        e.printStackTrace();
    } catch (WriteException e) {
        e.printStackTrace();
    }
    workbook.write();
    try {
        workbook.close();
    } catch (WriteException e) {

        e.printStackTrace();
    }
} catch (IOException e) {
    e.printStackTrace();
}

标签: javaandroidexcel

解决方案


很难说...因为变量a未使用,j并且xCor没有在任何地方定义。

但是不能i3 == j+1作为for循环的运行条件,因为条件永远不会为真,因此执行永远不会进入该控制流语句(死代码)。

最常见的情况是,您可能希望将循环索引与较小或等于运算符进行比较:

for (int i=1; i <= j; i++) { ... }

登录到控制台可以极大地帮助确定循环的实际作用,例如:

Log.d(LOG_TAG, "i3 = " + i3 );

另请参阅JavaDocs ...假设这是jxl.write.

与此类似,您最终可能会了解它是如何工作的。


推荐阅读