如何在android中创建excel文件?

时间:2014-02-12 09:49:08

标签: java android excel

我正在尝试在android中创建一个excel文件。但是,当我单击按钮创建文件时,我的应用程序崩溃了。

logcat的

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。

3 个答案:

答案 0 :(得分:3)

似乎找不到jxl.WorkbookSettings。将 Java Excel API.jar 添加到项目 libs 中,然后清理并构建项目。

按照以下步骤将添加外部库 JARS 添加到项目中:

  

右击项目 - > goto属性 - >点击位于左侧的“Java Build Path” - > goto库 - >你看   单击添加外部JARS按钮并添加。

答案 1 :(得分:1)

在Android Studio中,您可以执行以下操作: -

  1. 在您的应用项目中创建文件夹“lib”
  2. 复制jxl.jar并将其粘贴到“lib”文件夹
  3. 右键单击jxl.jar。选择添加为库
  4. 完成
  5. 现在清理并运行项目。

答案 2 :(得分: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;
    }
}