Создать excel в android

bean class

class Bean {
        String initial, firstName, middleName, lastName;

        Bean(String initial, String firstName, String middleName, String lastName) {
            this.initial = initial;
            this.firstName = firstName;
            this.middleName = middleName;
            this.lastName = lastName;
        }

        public String getInitial() {
            return initial;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getMiddleName() {
            return middleName;
        }

        public String getLastName() {
            return lastName;
        }

    }

code for creating ExcelSheet

sheet.addCell(new Label(0, 0, «NameInitial»));
sheet.addCell(new Label(columnNumber,rowNumber,dataString));

 File directory, sd, file;
    WritableWorkbook workbook;

    void createExcelSheet() {
        String csvFile = "ExcelsheetName.xls";
        sd = Environment.getExternalStorageDirectory();
        directory = new File(sd.getAbsolutePath());
        file = new File(directory, csvFile);
        WorkbookSettings wbSettings = new WorkbookSettings();
        wbSettings.setLocale(new Locale("en", "EN"));
        try {
            workbook = Workbook.createWorkbook(file, wbSettings);
            createFirstSheet();
            createSecondSheet();
            //closing cursor
            workbook.write();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void createFirstSheet() {
        try {
            List<Bean> listdata = new ArrayList<>();

            listdata.add(new Bean("mr","firstName1","middleName1","lastName1"));
            listdata.add(new Bean("mr","firstName1","middleName1","lastName1"));
            listdata.add(new Bean("mr","firstName1","middleName1","lastName1"));
            //Excel sheet name. 0 (number)represents first sheet
            WritableSheet sheet = workbook.createSheet("sheet1", 0);
            // column and row title
            sheet.addCell(new Label(0, 0, "NameInitial"));
            sheet.addCell(new Label(1, 0, "firstName"));
            sheet.addCell(new Label(2, 0, "middleName"));
            sheet.addCell(new Label(3, 0, "lastName"));

            for (int i = 0; i < listdata.size(); i++) {
                sheet.addCell(new Label(0, i + 1, listdata.get(i).getInitial()));
                sheet.addCell(new Label(1, i + 1, listdata.get(i).getFirstName()));
                sheet.addCell(new Label(2, i + 1, listdata.get(i).getMiddleName()));
                sheet.addCell(new Label(3, i + 1, listdata.get(i).getLastName()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    void createSecondSheet() {

        try {
            List<Bean> listdata = new ArrayList<>();
            listdata.add(new Bean("mr","firstName1","middleName1","lastName1"));
            listdata.add(new Bean("mr","firstName1","middleName1","lastName1"));
            listdata.add(new Bean("mr","firstName1","middleName1","lastName1"));
            //Excel sheet name. 0 (number)represents first sheet
            WritableSheet sheet = workbook.createSheet("sheet2", 0);
            // column and row title
            sheet.addCell(new Label(0, 0, "NameInitial"));
            sheet.addCell(new Label(1, 0, "firstName"));
            sheet.addCell(new Label(2, 0, "middleName"));
            sheet.addCell(new Label(3, 0, "lastName"));

            for (int i = 0; i < listdata.size(); i++) {
                sheet.addCell(new Label(0, i + 1, listdata.get(i).getInitial()));
                sheet.addCell(new Label(1, i + 1, listdata.get(i).getFirstName()));
                sheet.addCell(new Label(2, i + 1, listdata.get(i).getMiddleName()));
                sheet.addCell(new Label(3, i + 1, listdata.get(i).getLastName()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

Read data from ExcelSheet

 public void readDataFromExcelSheet() {
        List<Bean> listOfBean = new ArrayList<>();
        try {
            String filename = "ExcelsheetName.xls";
            // Creating Input Stream
            File sd = Environment.getExternalStorageDirectory();
            File directory = new File(sd.getAbsolutePath());
            File file = new File(directory, filename);
            Workbook workbook = null;
            WorkbookSettings ws = new WorkbookSettings();
            ws.setGCDisabled(true);
            workbook = Workbook.getWorkbook(file, ws);

            int noOfSheets = workbook.getNumberOfSheets();//this is return how many sheets available in excelsheet
            String sheetsNames[] = workbook.getSheetNames();//this is return all sheets names available in excelsheet
            for (int x = 0; x < noOfSheets; x++)//here take all sheets
            {
                Sheet sheet = workbook.getSheet(x);//here i taken first sheet
                int rowCount = sheet.getRows();//count total number of row or data in that sheet
                for (int i = 0; i < rowCount; i++) {//take every row data
                    Cell[] column = sheet.getRow(i);//take all data of one row

                /*
                 for taking one by one column data 
                */
                    for (int j = 0; j < column.length; j++) {//take every column data of row
                        System.out.print("" + column[j].getContents() + "t");//take one by one data
                    }
                /*
                 for taking column data  
                */
                    listOfBean.add(new Bean(column[0].getContents(), column[1].getContents(), column[2].getContents(), column[3].getContents()));

                }

//                if you want take different data from different sheets then use switch case
                Sheet sheet1;
                int rowCount1;
                switch (x) {
                    case 0:
                        //write code for sheet 0 read data
                        sheet1 = workbook.getSheet(0);//here i taken first sheet
                        rowCount1 = sheet1.getRows();//count total number of row or data in that sheet
                        for (int i = 0; i < rowCount1; i++) {//take every row data
                            Cell[] column = sheet1.getRow(i);//take all data of one row
                            listOfBean.add(new Bean(column[0].getContents(), column[1].getContents(), column[2].getContents(), column[3].getContents()));
                        }
                        break;
                    case 1:
                        //write code for sheet 1 read data
                        sheet1 = workbook.getSheet(1);//here i taken first sheet
                        rowCount1 = sheet1.getRows();//count total number of row or data in that sheet
                        for (int i = 0; i < rowCount1; i++) {//take every row data
                            Cell[] column = sheet1.getRow(i);//take all data of one row
                            listOfBean.add(new Bean(column[0].getContents(), column[1].getContents(), column[2].getContents(), column[3].getContents()));
                        }
                        break;
                }


            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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


I have a very simple question: How to create .docx and .xlsx files on Android. Before someone marks this as duplicate, let me tell you that I have extensively tried creating them using Apache POI and my attempts are described in these questions:

java.lang.NoClassDefFoundError while creating a .xlsx file using Apache POI

Creating a .docx file using poi-ooxml jar file

However, as described in those links, I am getting the java.lang.verify error. These are the jar files I have finally imported into my reference libraries:

  • dom4j-1.6.1.jar

  • poi-3.10-FINAL-20140208.jar

  • poi-ooxml-3.10-FINAL-20140208.jar

  • stax-api-1.0.1.jar

  • xmlbeans-2.3.0.jar

  • poi-ooxml-schemas-3.10-FINAL-20140208.jar

  • commons-codec-1.5.jar

  • commons-logging-1.1.jar

  • junit-4.11.jar

  • log4j-1.2.13.jar

but now it doesn’t compile at all, and says this on the console

Ill-advised or mistaken usage of a core class (java.* or javax.*)
when not building a core library.

This is often due to inadvertently including a core library file
in your application's project, when using an IDE (such as
Eclipse). If you are sure you're not intentionally defining a
core class, then this is the most likely explanation of what's
going on.

However, you might actually be trying to define a class in a core
namespace, the source of which you may have taken, for example,
from a non-Android virtual machine project. This will most
assuredly not work. At a minimum, it jeopardizes the
compatibility of your app with future versions of the platform.
It is also often of questionable legality.

If you really intend to build a core library -- which is only
appropriate as part of creating a full virtual machine
distribution, as opposed to compiling an application -- then use
the "--core-library" option to suppress this error message.

If you go ahead and use "--core-library" but are in fact
building an application, then be forewarned that your application
will still fail to build or run, at some point. Please be
prepared for angry customers who find, for example, that your
application ceases to function once they upgrade their operating
system. You will be to blame for this problem.

If you are legitimately using some code that happens to be in a
core package, then the easiest safe alternative you have is to
repackage that code. That is, move the classes in question into
your own package namespace. This means that they will never be in
conflict with core system classes. JarJar is a tool that may help
you in this endeavor. If you find that you cannot do this, then
that is an indication that the path you are on will ultimately
lead to pain, suffering, grief, and lamentation.

[2014-02-19 16:59:24 - test] Dx 1 error; aborting
[2014-02-19 16:59:24 - test] Conversion to Dalvik format failed with error 1

Please advise as to what I am to do.

EDIT:

My end purpose is: I wish to create .docx and .xlsx files and add some content to them. Once the files are created, I should be able to successfully view them on the PC system which I have connected the phone to.

EDIT 2: Found a workaround to generate .xlsx files by removing all these dependencies and using jspreadsheet-1.0 jar file. But I still don’t know what to do for .docx files.

UPDATED QUESTION:

It seems my problem lies with using the POI jar files which is not supported by Android. Can someone please supply me the link where I can get POI specifically for Android?

Or, can someone please tell me how to create .docx files to which I can add content, and such that they can be viewed?

Электронные таблицы используются людьми разных видов деятельности – как профессиональной, так и любительской. Но доступ к привычному Экселю на ПК есть не всегда, да и работать с телефона иногда удобнее. Есть несколько популярных табличных редакторов для Android, не уступающих по функционалу компьютерным.

Google Таблицы

Google Таблицы – это бесплатное приложение на андроид, предназначенное для работы с таблицами. Функционал позволяет:

  • создавать таблицы любого размера и сложности, редактировать их;
  • открывать чужие файлы соответствующего типа, к которым владелец дал доступ, редактировать и сохранять их;
  • редактировать документы совместно с другими пользователями (удобно в работе и ведении проектов);
  • просматривать историю изменений;
  • добавлять комментарии, редактировать их, удалять;
  • работать оффлайн;
  • настраивать параметры автосохранения;
  • вносиить в файлы формулы и диаграммы, сортировать и группировать данные, задавать параметры форматирования и настраивать автоматизацию тех или иных действий;
  • работать с документами, созданными в Microsoft Excel;
  • анализировать данные в документах.

Microsoft Excel: создание таблиц и работа с ними

Microsoft Excel: создание таблиц и работа с ними – это приложение на андроид для полноценной работы с таблицами, аналог компьютерной программы Microsoft Excel. Здесь можно:

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

Создать и экспортировать электронную таблицу Excel

«Создать и экспортировать электронную таблицу Excel» – это бесплатное приложение на андроид, в котором доступны все базовые функции Excel, но нет дополнительных, за счет чего экономится место в телефоне. Интерфейс не перегружен и понятен даже тем пользователям, которые плохо разбираются в Excel. Здесь можно:

  • создавать таблицы, аналогичные Excel, и работать с ними (добавлять и удалять столбцы и строки, работать с текстом и дополнительными элементами, вставлять формулы и выполнять соответствующие задачи и т. п.);
  • включать функцию «Упрощенная форма», при которой отсекается множество возможностей, зато интерфейс становится проще и легче (актуально для работы с текстом и данными чисел);
  • искать информацию по документу;
  • экспортировать документы в XLS или XLSX и открывать их в Excel, даже если изначально формат был другим;
  • импортировать данные Excel;
  • работать в оффлайн-режиме с сохранением доступа ко всему функционалу, за исключением возможности поделиться документом с кем-либо или отправить его в печать беспроводным способом;
  • использовать готовые шаблоны или создавать собственные.

Таблица заметки – Мобильная карманная база данных

«Таблица заметки – Мобильная карманная база данных» – это бесплатное приложение для андроид, предназначенное для работы с информацией, оформленной в таблицы. Здесь можно:

  • создавать таблицы данных и редактировать их как самостоятельно, так и в команде одобренных пользователей;
  • вводить информацию не только при помощи ручного ввода на клавиатуре телефона, но и другими способами (надиктовывать на микрофон, фотографировать данные, синхронизировать с картами или контактами, рисовать пальцем по экрану и т. п.);
  • автоматически или вручную создавать графики и диаграммы для визуализации;
  • включать напоминания для себя и подключенных к аккаунту коллег.

Благодаря синхронизации с другими пользователями и широкому функционалу, здесь с удобством можно:

  • отправлять команды коллегам и сотрудникам;
  • вести рабочие отчеты;
  • контролировать подчиненных;
  • вести любые базы данных и регулировать их содержание в любое время.

xlsx viewer: xls file viewer

XLSX viewer: XLS file viewer & Reader – это мобильное приложение на андроид, предназначенное для открытия и чтения форматов XLS и XLSX (то есть созданных в Excel). Оно правильно открывает таблицы с любым содержанием, даже если в них много графиков, диаграмм и других сложных для форматирования объектов в соответствии с телефонным экраном. Здесь качественно настроены функции поиска, перемещения по документу, перелистывание страниц и многое другое.

Помимо просмотра самого файла, в приложении можно посмотреть анализ содержащихся в нем данных. Есть и минимальный функционал редактирования: можно что-нибудь создать, удалить, скопировать, перенести, добавить, но более серьезных опций не предусмотрено.

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

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

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.

Понравилась статья? Поделить с друзьями:
  • Создать datamatrix в excel
  • Создания надписей ms word
  • Создать com объект excel
  • Создания макросов в таблицах word
  • Созданный сайт в word