Java 如何在android中创建excel文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21724192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:19:18  来源:igfitidea点击:

How to create excel file in android ?

javaandroidexcel

提问by general_bearbrand

I'm trying to create an excel file in android. But when I click the button to create the file, my app crashes.

我正在尝试在 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();
        }
    }

}

Btw, I used Java Excel API.

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

采纳答案by M D

It seems like jxl.WorkbookSettingsnot found. add Java Excel API.jarinto project libsand clean and built your project.

好像jxl.WorkbookSettings没找到。将Java Excel API.jar添加到项目库中并清理和构建您的项目。

Follow this steps to add external libraryor JARSinto your project:

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

right click project->goto properties ->click on "Java Build Path" located on left side-> goto libraries ->you see Add External JARS button click on it and add.

右键单击项目-> 转到属性-> 单击位于左侧的“Java 构建路径”-> 转到库-> 您会看到添加外部 JARS 按钮,单击它并添加。

回答by PraKi

In Android Studio you can do as follow:-

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

  1. Create a folder "lib" in your app project
  2. Copy jxl.jar and paste it in "lib" folder
  3. Right Click on the jxl.jar. Select Add as Library
  4. Finish
  1. 在您的应用项目中创建一个文件夹“lib”
  2. 复制 jxl.jar 并将其粘贴到“lib”文件夹中
  3. 右键单击 jxl.jar。选择添加为库
  4. 结束

Now Clean and Run the project.

现在清理并运行项目。

回答by Balaji Bal

***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;
    }
}