如何在安卓手机上创建Excel文件?

3

我想在安卓设备上创建一个Excel文件。但是当我点击按钮创建文件时,我的应用程序崩溃了。

日志

02-12 17:43:48.287: E/dalvikvm(25342): Could not find class 'jxl.WorkbookSettings', referenced from method lmf.test7.MainActivity.onClick
02-12 17:43:51.257: E/AndroidRuntime(25342): FATAL EXCEPTION: main
02-12 17:43:51.257: E/AndroidRuntime(25342): java.lang.NoClassDefFoundError: jxl.WorkbookSettings
02-12 17:43:51.257: E/AndroidRuntime(25342):    at lmf.test7.MainActivity.onClick(MainActivity.java:44)
02-12 17:43:51.257: E/AndroidRuntime(25342):    at android.view.View.performClick(View.java:4212)
02-12 17:43:51.257: E/AndroidRuntime(25342):    at android.view.View$PerformClick.run(View.java:17476)
02-12 17:43:51.257: E/AndroidRuntime(25342):    at android.os.Handler.handleCallback(Handler.java:800)
02-12 17:43:51.257: E/AndroidRuntime(25342):    at android.os.Handler.dispatchMessage(Handler.java:100)
02-12 17:43:51.257: E/AndroidRuntime(25342):    at android.os.Looper.loop(Looper.java:194)
02-12 17:43:51.257: E/AndroidRuntime(25342):    at android.app.ActivityThread.main(ActivityThread.java:5371)
02-12 17:43:51.257: E/AndroidRuntime(25342):    at java.lang.reflect.Method.invokeNative(Native Method)
02-12 17:43:51.257: E/AndroidRuntime(25342):    at java.lang.reflect.Method.invoke(Method.java:525)
02-12 17:43:51.257: E/AndroidRuntime(25342):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
02-12 17:43:51.257: E/AndroidRuntime(25342):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-12 17:43:51.257: E/AndroidRuntime(25342):    at dalvik.system.NativeStart.main(Native Method)

MainActivity

public class MainActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View arg0) {

        String Fnamexls="testfile"  + ".xls";

        File sdCard = Environment.getExternalStorageDirectory();

        File directory = new File (sdCard.getAbsolutePath() + "/newfolder");
        directory.mkdirs();

        File file = new File(directory, Fnamexls);

        WorkbookSettings wbSettings = new WorkbookSettings();
        wbSettings.setLocale(new Locale("en", "EN"));

        WritableWorkbook workbook;
        try {
            int a = 1;
            workbook = Workbook.createWorkbook(file, wbSettings);
            WritableSheet sheet = workbook.createSheet("First Sheet", 0);
            Label label = new Label(0, 2, "SECOND");
            Label label1 = new Label(0,1,"first");
            Label label0 = new Label(0,0,"HEADING");
            Label label3 = new Label(1,0,"Heading2");
            Label label4 = new Label(1,1,String.valueOf(a));

            try {
                sheet.addCell(label);
                sheet.addCell(label1);
                sheet.addCell(label0);
                sheet.addCell(label4);
                sheet.addCell(label3);
            } 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();
        }
    }

}

顺便说一下,我使用了Java Excel API。

似乎找不到 jxl.WorkbookSettings。将 Java Excel API.jar 添加到项目的 libs 中,然后清理并构建您的项目。 - M D
无法找到类“jxl.WorkbookSettings”。 - DevZer0
@MD - 我该如何将它添加到libs文件夹中?当我尝试将其添加到我的项目中时,我的项目会创建一个名为“Referenced Libraries”的新文件夹,并将其添加到其中。 - general_bearbrand
1
@speedsir,您错了。请在您的项目中创建一个名为“libs”的文件夹,并将此“.jar”文件添加到其中。 - M D
2
@speedsir 或者 右键项目->属性->库->你会看到“添加外部JARS”按钮,点击它并添加。 - M D
@MD - 谢谢您先生。没有错误。但是我不知道为什么在我的SD卡中看不到任何“newfolder”文件夹。我想我会就这个问题再问一个问题。 - general_bearbrand
3个回答

3
似乎找不到 jxl.WorkbookSettings。将 Java Excel API.jar 添加到项目的 libs 中,然后清理和构建您的项目。
按照以下步骤将外部库或 JARS 添加到您的项目中:
右键单击项目->选择属性->点击左侧的 "Java Build Path"->选择库->点击 "添加外部 JARS" 按钮并添加。

1
***use this code with jar file poi-3.7.jar***

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    Button Excel;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Excel = (Button)findViewById(R.id.Excel);
        Excel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveExcelFile("MyExcel.xls");
            }
        });
    }

    private static boolean saveExcelFile(String fileName) {
        String path;
        File dir;
        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            Log.e("Failed", "Storage not available or read only");
            return false;
        }
        boolean success = false;

        //New Workbook
        Workbook wb = new HSSFWorkbook();

        Cell c = null;

        //Cell style for header row
        CellStyle cs = wb.createCellStyle();
        cs.setFillForegroundColor(HSSFColor.LIME.index);
        cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        //New Sheet
        Sheet sheet1 = null;
        sheet1 = wb.createSheet("myOrder");

        // Generate column headings
        Row row = null;

        row = sheet1.createRow(0);

        c = row.createCell(0);
        c.setCellValue("Item Number");
        c.setCellStyle(cs);

        c = row.createCell(1);
        c.setCellValue("Quantity");
        c.setCellStyle(cs);

        c = row.createCell(2);
        c.setCellValue("Price");
        c.setCellStyle(cs);

        sheet1.setColumnWidth(0, (15 * 500));
        sheet1.setColumnWidth(1, (15 * 500));
        sheet1.setColumnWidth(2, (15 * 500));

        int val = 0;
        int k = 1;
        for(int i=1;i<12;i++){
            row = sheet1.createRow(k);
            for(int j=0;j<3;j++){
                c = row.createCell(j);
                c.setCellValue(val);
                c.setCellStyle(cellStyle);
                val++;
            }
            sheet1.setColumnWidth(i, (15 * 500));
            k++;
        }

        path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/EXCEL/";
        dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, fileName);
        FileOutputStream os = null;

        try {
            os = new FileOutputStream(file);
            wb.write(os);
            Log.w("FileUtils", "Writing file" + file);
            success = true;
        } catch (IOException e) {
            Log.w("FileUtils", "Error writing " + file, e);
        } catch (Exception e) {
            Log.w("FileUtils", "Failed to save file", e);
        } finally {
            try {
                if (null != os)
                    os.close();
            } catch (Exception ex) {
            }
        }
        return success;
    }

    public static boolean isExternalStorageReadOnly() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
            return true;
        }
        return false;
    }

    public static boolean isExternalStorageAvailable() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
            return true;
        }
        return false;
    }
}

1
在Android Studio中,您可以按照以下步骤操作:
  1. 在您的应用项目中创建一个名为“lib”的文件夹
  2. 复制jxl.jar并粘贴到“lib”文件夹中
  3. 右键单击jxl.jar。选择“添加为库”
  4. 完成
现在清理并运行项目。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接