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.

The main Java code is copied below also for reference:

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();
    }
}

}

#android #mobile-apps

How to create an Excel file from your Android App?
3.05 GEEK