Android studio таблица excel

import android.os.Bundle;

import android.view.View;

import android.widget.ProgressBar;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import androidx.core.widget.NestedScrollView;

import androidx.recyclerview.widget.LinearLayoutManager;

import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.Response;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.JsonObjectRequest;

import com.android.volley.toolbox.Volley;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ArrayList<UserModal> userModalArrayList;

    private UserRVAdapter userRVAdapter;

    private RecyclerView userRV;

    private ProgressBar loadingPB;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        userModalArrayList = new ArrayList<>();

        userRV = findViewById(R.id.idRVUsers);

        loadingPB = findViewById(R.id.idPBLoading);

        getDataFromAPI();

    }

    private void getDataFromAPI() {

        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

            @Override

            public void onResponse(JSONObject response) {

                loadingPB.setVisibility(View.GONE);

                try {

                    JSONObject feedObj = response.getJSONObject("feed");

                    JSONArray entryArray = feedObj.getJSONArray("entry");

                    for(int i=0; i<entryArray.length(); i++){

                        JSONObject entryObj = entryArray.getJSONObject(i);

                        String firstName = entryObj.getJSONObject("gsx$firstname").getString("$t");

                        String lastName = entryObj.getJSONObject("gsx$lastname").getString("$t");

                        String email = entryObj.getJSONObject("gsx$email").getString("$t");

                        String avatar = entryObj.getJSONObject("gsx$avatar").getString("$t");

                        userModalArrayList.add(new UserModal(firstName, lastName, email, avatar));

                        userRVAdapter = new UserRVAdapter(userModalArrayList, MainActivity.this);

                        userRV.setLayoutManager(new LinearLayoutManager(MainActivity.this));

                        userRV.setAdapter(userRVAdapter);

                    }

                } catch (JSONException e) {

                    e.printStackTrace();

                }

            }

        }, new Response.ErrorListener() {

            @Override

            public void onErrorResponse(VolleyError error) {

                Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show();

            }

        });

        queue.add(jsonObjectRequest);

    }

}

Содержание

  1. Manipulating Excel Files in Android using the Apache POI Library
  2. Prerequisites
  3. Getting started
  4. App-level build.gradle
  5. Project-level build.gradle
  6. Storage Permissions
  7. Creating and adding data to the Spreadsheet
  8. 1. Creating a Spreadsheet
  9. 2. Adding a workbook
  10. 3. Creating cells for the worksheets.
  11. 4. Adding data to the cells
  12. Reading the Excel file and performing statistical computations
  13. 1. Retrieving the Excel file
  14. 2. Retrieving the workbook
  15. 3. Selecting the worksheet
  16. Performing the statistical computations
  17. 1. Mean
  18. 2. Variance
  19. 3. Standard variation
  20. Output
  21. Conclusion
  22. Creating/Reading an Excel file in Android.
  23. Excel Sheet accessing through android application in very few lines of code.
  24. Steps to achieve the target:-
  25. 1) Create a project in android “Exel_Example” and fill all the required details.
  26. 2) In AndroidManifest.xml file add “WRITE_EXTERNAL_STORAGE ” permission as we require to access the external storage for saving the Excel file.
  27. 3) Add the poi-3.7.jar (or updated version) that you have downloaded from the link provided above. Add this jar to your project’s External Jars.
  28. 4)Create a new class named “MainActivity.java”
  29. To read the contents of the file have a look at the function “readExcelFile” below
  30. Related Reading
  31. Here is the entire code.
  32. MainActivity.java
  33. Create a main.xml file in “layout” folder
  34. programmerworld
  35. Know all about MATLAB/ Simulink, Selenium Testing, Android apps development and much more …
  36. How to create an Excel file from your Android App?
  37. Share this:
  38. Like this:
  39. 25 comments

Manipulating Excel Files in Android using the Apache POI Library

February 11, 2022

When processing data for a custom on-device model or creating your spreadsheet app, you need to know how to manipulate spreadsheet format files. In this article, we will look at creating a spreadsheet file, opening it, and performing common statistical functions in it.

We will simulate student names and scores. The process would require a lot of code and research when done from scratch since Java does not have support for Excel file formats. Luckily, we have the Apache POI library.

Apache POI is an open-source library that provides a Java API for manipulating file formats based on the Office Open XML (OOXML) and OLE2 standards from Microsoft. Apache POI releases are available under the Apache License (V2.0).

Based on the definition, we get a clue that this library can also be used to manipulate Word and PowerPoint (slide) file formats.

Apache POI has two formats for manipulating Excel (Spreadsheet) files:

  • Horrible Spreadsheet Format (HSSF)
  • XML Spreadsheet Format (XSSF)

HSSF is used for .xls formats while XSSF is used for .xlsx formats. We will be using XSSF in this tutorial.

NOTE: I will be using the words Excel and Spreadsheet interchangeably.

Prerequisites

  • An understanding of Kotlin. A pre-exposure to working with the file system is a plus.
  • A basic understanding of Excel/Spreadsheets. One should be well versed with terminologies like cells, values, workbooks, sheets, etc.
  • Working with Android development environments and the general ecosystem. Though not so necessary, working knowledge of the Gradle may come in handy as we will be adding dependencies using the Gradle files.

Getting started

After creating your app, modify the app-level and project-level Gradle files as follows:

App-level build.gradle

In the dependencies section, add the following lines:

Project-level build.gradle

Add this to the repositories section:

After the build process is done, we proceed to write the logic for creating and reading the Spreadsheet files in the MainActivity class.

Storage Permissions

Don’t forget to add these permissions in your AndroidManifest file:

Creating and adding data to the Spreadsheet

To achieve this, we follow the following steps:

  1. Create a Spreadsheet in the app’s directory.
  2. Add a workbook to the Spreadsheet. At this step, we will also look at creating worksheets.
  3. Create cells for the worksheets.
  4. Add data to the cells.

1. Creating a Spreadsheet

We will use a function called createExcelFile(ourWorkbook: Workbook) . It accepts a workbook object which we will discuss in the next step. First, we get to access our app’s directory. Next, we check whether it exists. If it does not exist, we create a directory:

Thereafter, we create an Excel file named test.xlsx and write our workbook to the file using a file output stream. You can give it a name of your choice:

The full method code is as follows:

2. Adding a workbook

In this method, we create a workbook object from the XSSFWorkbook class. A worksheet named statSheet is added to the workbook. The addData() method is then called to populate the sheet with data. We will look at this function later.

The newly created workbook is returned after the method createWorkbook() finishes executing. For the worksheet creation, Apache POI’s method called createSheet() is used:

3. Creating cells for the worksheets.

Three parameters are passed in:

  1. sheetRow — The row where data is added.
  2. columnIndex — The column number where a value is added.
  3. cellValue — The value to be added to the cell.

In the createCell() method, we create a cell at a passed-in index and add the value to it. The library’s setCellValue(value) method is used in adding values to cells.

4. Adding data to the cells

This method is quite simple. We create rows and add data to them in the worksheet passed in as a parameter:

Check out this blog which explains about adding headers and setting header styles.

Reading the Excel file and performing statistical computations

Just like creating and populating data to the Spreadsheet, we will follow these steps:

  1. Retrieve the Excel file from the app’s directory.
  2. Retrieve the workbook.
  3. Select the worksheet we will be working on.
  4. Perform statistical computations on the data.

1. Retrieving the Excel file

We use a function called getExcelFile() . In the let scope, we check if the file exists and return it if it does. The function may return null since a file may not be present. That’s why it is made nullable:

2. Retrieving the workbook

Here, we read the workbook from the loaded spreadsheet as an input stream and then return the workbook:

3. Selecting the worksheet

We use the library’s getSheetAt(position) method for this. After the selection, we return it. Since a worksheet may not be present, this method may return a null value:

Performing the statistical computations

Three basic statistical functions are done:

Let’s have a look at them:

1. Mean

We sum all the values then divide the total value by the number of students. An array from which we will get the values is passed in as a parameter:

2. Variance

Squared difference from the mean. The logic will then be subtracting each value from the mean, squaring it, and then finding an average. Therefore, our function will have two parameters, the values array and the mean:

3. Standard variation

This is the square root of the variance:

The Apache POI library also provides built-in Excel functions such as SUMIF, COUNTIF, etc. If interested, check them out here.

Output

After running the app, we should get the following output:

The Excel file will resemble the one below:

You can access the Excel file in your Device Explorer via the IDE by following these steps: View -> Tool Windows -> Device File Explorer -> data > your-package-name -> files.

The GitHub repository can be found here and the APK file here.

Conclusion

In this tutorial, We have looked at creating an Excel file, reading the file, and performing common statistical functions on the data in the file. I hope you found this article insightful. You can customize the code and do more with it. For example, you can add dynamic input, create recycler adapters for data in the Excel files, etc.

Источник

Creating/Reading an Excel file in Android.

Home > Creating/Reading an Excel file in Android.

Its easy to store records in database via android application. But what’s the use of it when we cannot get the records on a sheet of paper.

Here’s a simple and systematic solution to get your records in an excel sheet in Android.

Excel Sheet accessing through android application in very few lines of code.

To achieve this download poi-3.7.jar or later from the following reference:-

Note:- make sure its a jar file for eclipse.

Steps to achieve the target:-

1) Create a project in android “Exel_Example” and fill all the required details.

2) In AndroidManifest.xml file add “WRITE_EXTERNAL_STORAGE ” permission as we require to access the external storage for saving the Excel file.

3) Add the poi-3.7.jar (or updated version) that you have downloaded from the link provided above. Add this jar to your project’s External Jars.

For that go to your project’s properties –> click on java Buildpath –> add External Jars –> Browse the jar.

4)Create a new class named “MainActivity.java”

Here we have 2 functionality to cover.

First is to save the Excel File and other is to read the contents of the Excel File.

To save a Excel file, check out the function “saveExcelFile” below

private static boolean saveExcelFile(Context context, String fileName) < // check if available and not read only if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) < Log.e(TAG, “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); //New Sheet Sheet sheet1 = null; sheet1 = wb.createSheet(“myOrder”); // Generate column headings Row 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)); // Create a path where we will place our List of objects on external storage File file = new File(context.getExternalFilesDir(null), 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; >

Here we pass the file name as the parameter to the function.

Row row = sheet1.createRow(0); c = row.createCell(0); c.setCellValue(“Item Number”); c.setCellStyle(cs);

This is how we add/enter the value in the cell.

The above code will add the value “Item Number” in the 0th row and 0th column.

To read the contents of the file have a look at the function “readExcelFile” below

Each and every entry in the cell will be printed in the log.

Here is the entire code.

MainActivity.java

Create a main.xml file in “layout” folder

In this xml file, add two buttons with id’s “writeExcel” and “readExcel” representing the “WriteExel” and “ReadExcel” buttons respectively.

Once you have done with all the above steps, your application is ready to test.

Источник

programmerworld

Know all about MATLAB/ Simulink, Selenium Testing, Android apps development and much more …

How to create an Excel file from your Android App?

This video shows the steps to create an Excel file in your Android App. It uses third party library (not available as in-built APIs) from org.apache.poi.

It hard-codes the file name and sheet name in the code. However, that can be taken as an input from the user.

For the content it takes the input from the user through an Edit Text widget. Though it uses a single line edit text but same can be done using a multi-line plain text (Edit text) user input.

It creates the file in the emulator’s external storage. However, any location on the mobile device can be used to create the file.

I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com

Like this:

Hello sir, i’ve tried this code. same as you wrote, but for me its not working. on button click nothing happends. and if i use progress dialog and dismiss the progress dialog after hssfWorkbook.write(fileOutputStream);
it doesn’t dismiss. which means the code is not writing the file at all. and of course not output.
i’ve tried many more methods with jar libraries with XSSWorkbook but nothing is working for me.
i would very much appreciate if you could help me.
Thank you

Did you try to debug the code? Any error or exception is thrown?

I also hope you have implemented the required library in your gradle file. Also, have set the Onclick attribute of the button.

If all the above is done and still gives issue then please paste your code here. We will check.

Cheers
Programmer World

Wow thank you sir for replying so fast .
I’ve debug the code . The log says no such location or file name found .
But the code is trying to make new once it shouldn’t be a problem I think .
But still I changed the directory and the file name and also tired it by creating new folder for it .
Still not working.
Once again Thank you for your reply.

Then the issue is that the file path location chosen is not correct. I have used the below line in my code:

private File filePath = new File(Environment.getExternalStorageDirectory() + “/Demo.xls”);

But check whether your mobile or emulator has this path. Else use any other path which exists on your device.

I hope the above information helps.

Cheers
Programmer World

hello sir I tried to create an xls file by using your steps mentioned above but it throws an IO exception : permission denied at this line:
filePath.createNewFile();
I had given all the required permissions in the manifests and java file but still stuck .
I would be very thankful if you help me
Thank you

Please check the below:
– You have given WRITE TO EXTERNAL STORAGE (WRITE_EXTERNAL_STORAGE) permission both in Java code and Manifest file.
– In the first time usage, App would ask from user to grant this permission. Please make sure user has granted this permission to the App.
– Also, please check that the file path (folder location) exists. Different phones may have different locations. So, ensure that the path you are using in code is valid.

The above checks should help in debugging the IO (input-output) exception you are getting. If the issue still persists then please comment here.

Cheers
Programmer World

Isn’t this function Environment.getExternalStorageDirectory() is sufficient for making an excel file? i had given permissions in both java code and manifest. but it is also showing a warning that ” WRITE_EXTERNAL_STORAGE no longer provides write access when targeting Android 10+”
please help sir 😐

Hello sir , thank you for your response.
I’ve corrected that issue by putting legacy storage true in manifest file .
Thank you very much for everything

Oh, good to know this. Good that you have found another solution.

Cheers
Programmer World

Android:requestLagecyExrernalStorage = “true”
In manifest application

For Android 10 (API level 29) onwards the External Storage related permissions have changed a bit. Now, one can directly contribute to a well-defined media collections such as MediaStore.Downloads without requesting any storage-related permissions. (This is also mentioned in the android developer portal).

Alternatively, one can also write to the App specific data without requiring any Storage privilege. Use “getExternalFilesDir” API for this. An example of this can be found in my below webpage:

Источник

how to read excel file in android from asset folder

In this android tutorial, You are going to learn how to read excel file in android from asset folder using Apache POI.  What is android Apache POI lib? To Read / Write Excel file (.xls or .xlsx) there are two types of library available – 1) JXL and 2) Apache POI. But the first one- Java JXL does not support the Excel 2007+ “.xlsx” format; it only supports the old BIFF (binary) “.xls” format. Apache POI supports both with a common design. We will use asset manager class to read excel file from asset folder.

I will suggest you to use POI library only. Now you have understand what to use. Let move forward, to read excel file from asset folder, first create a excel file. In excel file, you can create any number of columns and sheets. for this android example, I am using three columns name as- sno, date, details. below is sample excel data-

sno date details
1 01-09-2018 details  about 1
2 02-09-2018 details about 2
3 03-09-2018 detais about 3
4 04-09-2018 details about 4

Step by Step Process

  1. Create a excel file & put in asset folder
  2. Add POI lib dependency
  3. Read excel file in android
  4. Run the code

Create a excel file & put in asset folder

create a sample excel file as explain in above paragraph. You can create more columns and sheet. But if you are trying this code first time, so please work with three columns only. now same the file name as “myexcelsheet.xls” Go to android project directory and open your android project. Go inside folder app -> src ->main. There you will see two folder name as java and res. Now create a new folder here name as assets and put myexcelsheet.xls file inside it.

Note -: save file in .xls format only for this example. to read .xlsx file, there is slight difference in code.

Login & Download code

Add POI lib dependency in gradle

Now create a new project in android studio and add gradle dependency for apache POI library using below code

implementation "org.apache.poi:poi:3.17"
implementation "org.apache.poi:poi-ooxml:3.17"

To display excel sheet data on phone screen, I am using a simple textview. By default android studio create a textview on activity_main.xml file.

material design example

activity-main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="blueappsoftware.readexcelfile.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Excel Data below -"
        android:id="@+id/textview"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:lineSpacingExtra="2dp"
        android:gravity="center" />

</LinearLayout>

Now open java activity file – ActivityMain.java. There are three important points-

  1. initialize asset manager
  2. open excel file
  3. initialize POI file system
  4. open work book
InputStream myInput;
// initialize asset manager
AssetManager assetManager = getAssets();
//  open excel file name as myexcelsheet.xls
myInput = assetManager.open("myexcelsheet.xls");
// Create a POI File System object
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

// Create a workbook using the File System
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

// Get the first sheet from workbook
HSSFSheet mySheet = myWorkBook.getSheetAt(0);

read first excel sheet

please look at above code -at last line, there is getSheetAt(0). That means read sheet index number zero. if you have multiple sheet on excel file you can pass index of sheet. index started from 0 means first sheet.

Now it’s time to read data from row and column of the sheet. The concept is – use a loop to read row one by one. On each row- read column one by one. Apache POI library provides the method to read row and column in loop.

 // We now need something to iterate through the cells. 
 Iterator<Row> rowIter = mySheet.rowIterator();

// check if there is more row available           
HSSFRow myRow = (HSSFRow) rowIter.next();

// check if there is more column available 
HSSFCell myCell = (HSSFCell) cellIter.next();

You can read value in column using cell object. For example – myCell.toString(); below it complete code of main activity

package blueappsoftware.readexcelfile;

import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import java.io.InputStream;
import java.util.Iterator;

public class MainActivity extends AppCompatActivity {
    String TAG ="main";
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textview);
        readExcelFileFromAssets();
    }

    public void readExcelFileFromAssets() {

        try {

            InputStream myInput;
            // initialize asset manager
            AssetManager assetManager = getAssets();
            //  open excel sheet
            myInput = assetManager.open("myexcelsheet.xls");
            // Create a POI File System object
            POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

            // Create a workbook using the File System
            HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

            // Get the first sheet from workbook
            HSSFSheet mySheet = myWorkBook.getSheetAt(0);

            // We now need something to iterate through the cells. 
            Iterator<Row> rowIter = mySheet.rowIterator();
            int rowno =0;
            textView.append("n");
            while (rowIter.hasNext()) {
                Log.e(TAG, " row no "+ rowno );
                HSSFRow myRow = (HSSFRow) rowIter.next();
                if(rowno !=0) {
                    Iterator<Cell> cellIter = myRow.cellIterator();
                    int colno =0;
                    String sno="", date="", det="";
                    while (cellIter.hasNext()) {
                        HSSFCell myCell = (HSSFCell) cellIter.next();
                        if (colno==0){
                            sno = myCell.toString();
                        }else if (colno==1){
                            date = myCell.toString();
                        }else if (colno==2){
                            det = myCell.toString();
                        }
                        colno++;
                        Log.e(TAG, " Index :" + myCell.getColumnIndex() + " -- " + myCell.toString());
                    }
                    textView.append( sno + " -- "+ date+ "  -- "+ det+"n");

                }
                rowno++;
            }

        } catch (Exception e) {
            Log.e(TAG, "error "+ e.toString());
        }
    }

}

Run the code

Run the code in device OR emulator. You can see in below picture, Excel sheet data is showing on Textview in android app.

how to read excel file in android

If you have any question, Please comment below.

Get more android tutorial:-

How to create PDF file in Android, Write Text, Image in PDF – Android code

How to read text file in android – read from internal/ external folder

author avatar

I am a full Stack Developer. My skills are — Flutter, Java, Android, PHP, Node.js, JavaScript, AJAX, WordPress, SQL & many more. I have developed Android App for Police department, eCommerce App, Restaurant App, Daily Bill Invoice, Daily news, Location based App etc.
If you have any query, Please WhatsApp me at +91-9144040888 Or email me at kamal.bunkar@blueappsoftware.com

This video shows the steps to create an Excel file in your Android App. It uses third party library (not available as in-built APIs) from org.apache.poi.

It hard-codes the file name and sheet name in the code. However, that can be taken as an input from the user.

For the content it takes the input from the user through an Edit Text widget. Though it uses a single line edit text but same can be done using a multi-line plain text (Edit text) user input.

It creates the file in the emulator’s external storage. However, any location on the mobile device can be used to create the file.

I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com

Source Code

package com.programmerworld.excelfileapp;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

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

public class MainActivity extends AppCompatActivity {

private EditText editTextExcel;
private File filePath = new File(Environment.getExternalStorageDirectory() + "/Demo.xls");

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

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, PackageManager.PERMISSION_GRANTED);

editTextExcel = findViewById(R.id.editText);
}

public void buttonCreateExcel(View view){
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet hssfSheet = hssfWorkbook.createSheet("Custom Sheet");

HSSFRow hssfRow = hssfSheet.createRow(0);
HSSFCell hssfCell = hssfRow.createCell(0);

hssfCell.setCellValue(editTextExcel.getText().toString());

try {
if (!filePath.exists()){
filePath.createNewFile();
}

FileOutputStream fileOutputStream= new FileOutputStream(filePath);
hssfWorkbook.write(fileOutputStream);

if (fileOutputStream!=null){
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

apply plugin: 'com.android.application'

android {
compileSdkVersion 29
buildToolsVersion "29.0.3"

defaultConfig {
applicationId "com.programmerworld.excelfileapp"
minSdkVersion 26
targetSdkVersion 29
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

implementation 'org.apache.poi:poi:3.17'

}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.programmerworld.excelfileapp">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="128dp"
android:layout_marginTop="60dp"
android:onClick="buttonCreateExcel"
android:text="@string/create_excel"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="78dp"
android:layout_marginTop="57dp"
android:ems="10"
android:hint="@string/your_text_here"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button"
android:autofillHints="" />
</androidx.constraintlayout.widget.ConstraintLayout>

<resources>
<string name="app_name">Excel File App</string>
<string name="create_excel">Create Excel</string>
<string name="your_text_here">Your text here ...</string>
</resources>
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.1"

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
google()
jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

App’s Output


Write_Excel_File_From_Android_Studio

You can Create a excel File From Android Studio —

Easy Steps —————- Step 1———

Download this Jxl Library File

Download Library

After Downloading this File Add this File to Your Android Studio —
Project ->app ->libs ->Pest the file

{if you cant understand this please checkout the screenshot 1 }

—————Step 2—————————

Add MultiDex in your build.gradle file (Module app)

apply plugin: ‘com.android.application’

// code 

 android {
     compileSdkVersion 28
     defaultConfig {
         applicationId "worldcup.cricketworldcup.mynewexcelwork"
         minSdkVersion 14
         targetSdkVersion 28
         multiDexEnabled true
         versionCode 1
         versionName "1.0"
         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
     }
     dexOptions {
         //incremental = true;
         preDexLibraries = false
         javaMaxHeapSize "4g"
     }

     packagingOptions {
         exclude 'META-INF/NOTICE.txt' // will not include NOTICE file
         exclude 'META-INF/LICENSE.txt' // will not include LICENSE file
     }

     buildTypes {
         release {
             minifyEnabled false
             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
         }
     }
 }

 dependencies {
     implementation fileTree(dir: 'libs', include: ['*.jar'])
     implementation 'com.android.support:appcompat-v7:28.0.0'
     implementation 'com.android.support.constraint:constraint-layout:1.1.3'
     testImplementation 'junit:junit:4.12'
     implementation 'com.android.support:multidex:1.0.1'
     androidTestImplementation 'com.android.support.test:runner:1.0.2'
     androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
 }

———Step 3 ———————————

  • Add this Permission Into your Manifest File :

Code

// code

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    

————Step 4 ——————

*Now Checkout the MainActivity.java file ———You can able to Create Your #Excel File Into Your Device Extralnal or Internal Storage
*For Making Normal File You can check Main2Activity .

————Step 5 ——————

Dont Forget To Use Permission . Without Permission it will not work .

Add Permission

// code
 
 
 
 public  boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.v(TAG,"Permission is granted");
                return true;
            } else {

                Log.v(TAG,"Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        }
        else { //permission is automatically granted on sdk<23 upon installation
            Log.v(TAG,"Permission is granted");
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
            //resume tasks needing this permission
        }
    }

Authors

  • Tasnuva Tabassum Oshin — IDevelopApps

License

This project is licensed under the MIT License — see the LICENSE.md file for details

Acknowledgments

  • For any Query Email Me — tasnuva.oshin12@gmail.com
  • My Youtube Channel — https://www.youtube.com/channel/UCf_kr77VNwQBTG2Xy1EBCkw
  • Thanks

Like this post? Please share to your friends:
  • Android games word games
  • Android app what the word
  • Android 4 pics one word
  • Andis smc 2 excel
  • Andis excel 5 speed