Android studio работа с excel

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

Содержание

  1. How to Read Data from Google Spreadsheet in Android?
  2. What we are going to build in this article?
  3. Step by Step Implementation
  4. Create an excel file programmatically in Android
  5. A Simple way to work with Excel in Android App
  6. Part 1- Writing Excel Sheet
  7. Prerequisites
  8. Write Excel File
  9. Android programmers blog
  10. Поиск по этому блогу
  11. понедельник, 17 февраля 2014 г.
  12. Работа с MS Excel в Android
  13. Creating/Reading an Excel in Android.
  14. Overview:
  15. However, we will only cover the following in this article:
  16. Downloading the JAR file
  17. Exporting jar as a dependency in Android Studio

How to Read Data from Google Spreadsheet in Android?

Many apps have to display statistical data inside their applications and they stores all their data in the excel file or a spreadsheet. But it is not every time possible to add the whole data in the database to use inside our app. In this article, we will take a look at reading this data from our Excel sheet in Android App in Android Studio.

What we are going to build in this article?

We will be building a simple application in which we will be displaying data from our excel sheet which we have already created and we will read the entries from that excel sheet and display that list of data in our recycler view. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add the below dependency in your build.gradle file

Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section.

// below line is use for image loading library

Источник

Create an excel file programmatically in Android

Sometimes we need to export data in an excel file. So below it will be step by step explanation.

As we are writing a file into storage so we need storage permission. Add storage permission on Manifest.

Now on your launcher activity “onCreate” method add the Apache POI api.

What is apache POI?

The Apache POI Project’s mission is to create and maintain Java APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft’s OLE 2 Compound Document format (OLE2). In short, you can read and write MS Excel files using Java. In addition, you can read and write MS Word and MS PowerPoint files using Java. Apache POI is your Java Excel solution (for Excel 97–2008). We have a complete API for porting other OOXML and OLE2 formats and welcome others to participate.

Just before creating the file ask storage write permission.

Now the main part, Creating a specific folder for the excel file, Creating the excel file itself, and insert data into excel file.

Creating a sheet

Inserting value in the sheet, You can add as many as column by increasing the index number of CELL_INDEX

Creating a folder and “FolderName” is the name of the folder you want to keep your file in the local storage. “FileName.xlsx” is the file name.

Inserting all data into the file and you are done.

Here is the full code with permission and writing data

Thanks, if face any problem feel free to comment.. 🙂 🙂

Источник

A Simple way to work with Excel in Android App

Part 1- Writing Excel Sheet

So, in today’s article you will learn writing of excel sheet in Android app with a very simple and easy way. To do this, we need to add libraries from Apache POI.

In App level gradle file, add below dependencies.

Prerequisites

Have previous knowledge about:
1- Kotlin
2- Save file in Android

Write Excel File

To create excel file, we first need to create Workbook from XSSFWorkbook and then need to create sheet to add data into it.

You can create multiple sheets in a single workbook by using the createSheet method of workbook.

In the first row of excel sheet, usually people create sheet header. So, below code will help you to create and understand header in excel sheet.

The maximum column width for an individual cell is 255 characters and it’s value in integer cannot be greater than 65280.

In the above code snippet, you can assign any color to the cell background or Foreground. For more details, you can see the implementation of setFillPattern method in CellStyle class. You can also customize the font style of the text of a cell including color.

To add data in the excel sheet, you need to create a row and need to add data to each cell of the row.

Create cell with row and column indexes and add value into it.

Now it’s time to create excel file from workbook in Android Directory.

Hurry!! creating and writing excel file in Android App successfully done.

For reading excel sheets please check Part-2. Next parts of updating excel sheet will be published soon. Please follow for more posts and different solutions to the problems in Android App.

Источник

Android programmers blog

Simply about difficult

Поиск по этому блогу

понедельник, 17 февраля 2014 г.

Работа с MS Excel в Android

Всем здрасте, сегодня я расскажу вам как читать поля из *.xls файла. Сперва я думал что это до ужаса трудно и все дела, а на деле оказалось проще пареной репы. Статья будет короткой так как тут рассказывать в принципе не много.

Для работы с MS Excel вам понадобятся библиотеки от Apache, которые называются POI, скачать вы их можете с официальной страницы Apache . Но я вам дам два главных файла которые нам нужны для чтения простого файла таблицы.

Файлы либ — раз , два

Дальше когда вы скачали эти файлы, закиньте их в своем проекте в папку libs/. Если они автоматически не импортировались в Build settings то кликайте правой кнопкой по ним и выберите Build -> add to build path, после этого либы должны импортироваться в проект.

Далее нам нужен файла, создайте простой Excel файл, я создал вот такой:

Кстати я ранее не говорил но желательно создавать файл образца Excel 97 — 2003, потому что далее начали делать файлы с другим шифрованием и почему то для чтения этих файлов нужны танцы с бубном.

Теперь файл который вы создали нужно положить в папку asset/ в которой обычно хранятся разного рода файлы. Далее мы будем из нее будем открывать наш .xls файл.

С подготовкой окончено, теперь приступим к программированию. Для начала выведем просто первые два стобца во втором поле. В нашей activity мы добавляем в OnCreate() вот такой код:

Я сильно не заморачивался и выводить буду в лог, так быстрей и проще (: Как видно код простой до безобразия, в начале открываем файл, дальше читаем лист с данными, и переходим к нужному полю и столбцу, и выводим то что нам нужно.

Для того что бы вывести все поля которые есть в файле вам нужно засунуть в цикл этот код, выглядеть он будет примерно вот так:

Вот собственно такой короткий экскурс в чтение файлов MS Excel, если лень создавать базы и все такое, то очень удобно использоваться именно такой способ.

У этой библиотеки очень большие возможности, больше можно прочесть в официальной документации на сайте Apache, а у меня все.

Источник

Creating/Reading an Excel in Android.

With the exponential increase in mobile devices, the ease of data accessibility has increased tenfold.

We can see all the data relevant to any domain on the mobile devices, for instance, the annual turnover of an organization, the number of employees who joined last month, etc. However, displaying the data on a mobile application is useful, although it becomes quite useless when we need to share the relevant data with the management or others. It is where exporting of data comes in handy and can be seen in most mobile applications today.

Overview:

We want to create a ‘Contact’ application of our own as shown in the video below.

In this application:

  • Initially, we will query the Contacts Content Provider in order to retrieve all the contacts present in the Android device.
  • Next, we would export all the contacts into an Excel workbook (.xls format)
  • Lastly, we will read data from the previously generated xls workbook and display the results in a recycler-view.
  • As a bonus feature, we can also share the excel via the supported applications (eg: Nearby Share, Bluetooth etc.)

You can find the code for this application here .

However, we will only cover the following in this article:

  1. Downloading the jar file.
  2. Exporting jar as a dependency in Android Studio.
  3. Creating an Excel workbook.
  4. Importing data (Reading) from an Excel workbook.
  5. Exporting data (Writing) into an Excel Workbook.

By the end of this article, you will be able to generate the below excel workbook:

Without wasting any time further, let us dive into it right away!

Downloading the JAR file

We will be making use of Apache’s POI project in order to achieve our goal. It is completely free and can be downloaded from here.

As per the official documentation:

You can read and write MS Excel files using Java. In addition, you can read and write MS Word and MS PowerPoint files using Java. Apache POI is your Java Excel solution (for Excel 97–2008).

So, not only can we use the POI for generating excel, it can be used for creating MS Word and MS Power point as well. However, it is beyond the scope of this article.

Exporting jar as a dependency in Android Studio

Next, we need to export the JAR as a dependency in Android Studio. I’ve depicted the same in a step-wise manner below:

Источник

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


Всем здрасте, сегодня я расскажу вам как читать поля из *.xls файла. Сперва я думал что это до ужаса трудно и все дела, а на деле оказалось проще пареной репы. Статья будет короткой так как тут рассказывать в принципе не много.

Для работы с MS Excel вам понадобятся библиотеки от Apache, которые называются POI, скачать вы их можете софициальной страницы Apache. Но я вам дам два главных файла которые нам нужны для чтения простого файла таблицы. 

Файлы либ — раздва

Дальше когда вы скачали эти файлы, закиньте их в своем проекте в папку libs/. Если они автоматически не импортировались в Build settings то кликайте правой кнопкой по ним и выберите Build -> add to build path, после этого либы должны импортироваться в проект.

Далее нам нужен файла, создайте простой Excel файл, я создал вот такой:
image

Кстати я ранее не говорил но желательно создавать файл образца Excel 97 — 2003, потому что далее начали делать файлы с другим шифрованием и почему то для чтения этих файлов нужны танцы с бубном.

Теперь файл который вы создали нужно положить в папку asset/ в которой обычно хранятся разного рода файлы. Далее мы будем из нее будем открывать наш .xls файл.

С подготовкой окончено, теперь приступим к программированию. Для начала выведем просто первые два стобца во втором поле. В нашей activity мы добавляем в OnCreate() вот такой код:

import java.util.Random;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        try {
            //открываем файл
            Workbook wb = WorkbookFactory.create(getAssets().open("test.xls"));
            //перем первую страницу
          Sheet sheet = wb.getSheetAt(0);
          //читаем первое поле (отсчет полей идет с нуля) т.е. по сути читаем второе
          Row row = sheet.getRow(1);
          //читаем столбцы
          Cell name = row.getCell(0);
          Cell age = row.getCell(1);
          //отображаем текстовые данные + цифровые
          Log.d("",name.getStringCellValue() + " " + age.getNumericCellValue());
          
         } catch(Exception ex) {
             return;
         }
    }
}

Вывод:

Коля 22.0

Я сильно не заморачивался и выводить буду в лог, так быстрей и проще (: Как видно код простой до безобразия, в начале открываем файл, дальше читаем лист с данными, и переходим к нужному полю и столбцу, и выводим то что нам нужно.

Для того что бы вывести все поля которые есть в файле вам нужно засунуть в цикл этот код, выглядеть он будет примерно вот так:

try {
            //открываем файл
            Workbook wb = WorkbookFactory.create(getAssets().open("test.xls"));
            //перем первую страницу
          Sheet sheet = wb.getSheetAt(0);
          //добавляем цикл для чтения всехзаполненых полей, getPhysicalNumberOfRows() знает точное количество
          for(int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
           Row row = sheet.getRow(i);
              //читаем столбцы
              Cell name = row.getCell(0);
              Cell age = row.getCell(1);
              //отображаем текстовые данные + цифровые
              Log.d("",name.getStringCellValue() + " " + age.getNumericCellValue());
          }
          
         } catch(Exception ex) {
             return;
         }

Вывод:

Вася 12.0
Коля 22.0
Игорь 23.0
Маша 45.0
Ирина 32.0

Вот собственно такой короткий экскурс в чтение файлов MS Excel, если лень создавать базы и все такое, то очень удобно использоваться именно такой способ.

У этой библиотеки очень большие возможности, больше можно прочесть в официальной документации на сайте Apache, а у меня все.

Исходники:

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