25

I have to create an excel file programatically. Is there is any API to create an excel file or some other ways?
EDIT on 7th Nov 2011
I tried example Create an Excel Spreadsheet from this link Create an Excel spredsheet
and I am getting NullPointerException at workbook.write();, Using this I can create excel file on SD card, but when I open that excel file using MS office 2007 I am getting Unable to read file message
Here the stack trace, ExcelStudy is my activity that uses WriteExcel class

W/System.err(  235): java.lang.NullPointerException
W/System.err(  235):    at jxl.biff.StringHelper.getUnicodeBytes(StringHelper.java:133)
W/System.err(  235):    at jxl.biff.FontRecord.getData(FontRecord.java:289)
W/System.err(  235):    at jxl.biff.WritableRecordData.getBytes(WritableRecordData.java:71)
W/System.err(  235):    at jxl.write.biff.File.write(File.java:132)
W/System.err(  235):    at jxl.biff.Fonts.write(Fonts.java:110)
W/System.err(  235):    at jxl.write.biff.WritableWorkbookImpl.write(WritableWorkbookImpl.java:699)
W/System.err(  235):    at comm.study.code.WriteExcel.write(WriteExcel.java:49)
W/System.err(  235):    at comm.study.code.ExcelStudy.createExcelFile(ExcelStudy.java:64)
W/System.err(  235):    at comm.study.code.ExcelStudy$1.onClick(ExcelStudy.java:47)
W/System.err(  235):    at android.view.View.performClick(View.java:2364)
W/System.err(  235):    at android.view.View.onTouchEvent(View.java:4179)
W/System.err(  235):    at android.widget.TextView.onTouchEvent(TextView.java:6541)
W/System.err(  235):    at android.view.View.dispatchTouchEvent(View.java:3709)
W/System.err(  235):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
W/System.err(  235):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
W/System.err(  235):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
W/System.err(  235):    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
W/System.err(  235):    at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
W/System.err(  235):    at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
W/System.err(  235):    at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
W/System.err(  235):    at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
W/System.err(  235):    at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err(  235):    at android.os.Looper.loop(Looper.java:123)
W/System.err(  235):    at android.app.ActivityThread.main(ActivityThread.java:4363)
W/System.err(  235):    at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(  235):    at java.lang.reflect.Method.invoke(Method.java:521)
W/System.err(  235):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
W/System.err(  235):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
W/System.err(  235):    at dalvik.system.NativeStart.main(Native Method)
Daniel F
  • 13,684
  • 11
  • 87
  • 116
Sandeep Kumar P K
  • 7,412
  • 6
  • 36
  • 40

5 Answers5

14

First You have to go to this link, from which you can download latest library:

http://www.apache.org/dyn/closer.cgi/poi/release/bin/poi-bin-3.9-20121203.tar.gz

After that Put below code on onCreate or onResume Mehod:

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet firstSheet = workbook.createSheet("Sheet No: 1");
HSSFSheet secondSheet = workbook.createSheet("Sheet No: 2");
HSSFRow rowA = firstSheet.createRow(0);
HSSFCell cellA = rowA.createCell(0);
cellA.setCellValue(new HSSFRichTextString("Sheet One"));
HSSFRow rowB = secondSheet.createRow(0);
HSSFCell cellB = rowB.createCell(0);
cellB.setCellValue(new HSSFRichTextString("Sheet two"));
FileOutputStream fos = null;
try {
    String str_path = Environment.getExternalStorageDirectory().toString();
    File file ;
    file = new File(str_path, getString(R.string.app_name) + ".xls");
    fos = new FileOutputStream(file);
    workbook.write(fos);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fos != null) {
        try {
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Toast.makeText(MainActivity.this, "Excel Sheet Generated", Toast.LENGTH_SHORT).show();
}

// To see this excel file go to File Explorer in eclipse -> SDCard Path -> Excel.xls -> Pull it -> See it.

Tibrogargan
  • 4,508
  • 3
  • 19
  • 38
user2368799
  • 1
  • 1
  • 2
  • i have data in json format, so how to convert into excel file ? – Karthi Jan 25 '17 at 06:32
  • @Karthi make a matrix of data and use a loop to put data inside the excel. for example: `Cell c; Sheet sheet1= wb.createSheet(fileName); int i=0;int j=0; for (ArrayList rowList:reportDataLOL) { Row row=sheet1.createRow(i++); for(String item:rowList) { c=row.createCell(j++); c.setCellValue(item); } j=0; }` reportDataLOL is arrayList of arrayList – sanidhya pal May 02 '17 at 13:19
  • @user2368799 Your above link gives 404 not found error. –  Oct 23 '17 at 06:49
  • java.lang.IllegalArgumentException: Invalid char (:) found at index (8) in sheet name 'Sheet No: 1' better remove : – Shubham AgaRwal Jun 10 '18 at 15:22
  • I am getting an exception like There is the solution for awt.Color. – shafeeq Aug 28 '20 at 10:23
  • what is next step after downloading that library? where I can put? – Ravi Vaniya Feb 10 '21 at 14:06
4

Firstly add these dependencies in your app's build.gradle: then follow other answers:

implementation 'org.apache.poi:poi:3.17'
implementation 'org.apache.poi:poi-ooxml:3.17'
Clean Coder
  • 496
  • 5
  • 12
  • In case we get a duplicate class error, here's how to solve it: https://stackoverflow.com/a/68139550/7710739 – Reejesh PK Jun 26 '21 at 05:39
4

You could try http://jexcelapi.sourceforge.net/ (see this tutorial for some help), or Apache POI for writing to or reading from Excel files.

Amos M. Carpenter
  • 4,848
  • 4
  • 42
  • 72
  • 1
    Thanks for the help, I have tried this, I am getting NullpointerException during `workbook.write();` code. How can I rectify this? – Sandeep Kumar P K Nov 04 '11 at 10:41
  • 1
    @Sandy: Your question was about APIs to create Excel files - I've given you two examples, and I'm glad to hear you tried out the recommended tutorial, but I'm afraid I can't help with your NullPointerException without seeing some code and a stack trace (NPEs can have many causes...). I'd recommend asking a new, more specific question; you're welcome to leave a link to it here in the comments so I can see it. – Amos M. Carpenter Nov 05 '11 at 11:16
  • @Sandy: Seems to be the same issue as http://stackoverflow.com/questions/7119462/problem-in-creating-spreadsheetxls-file which hasn't been answered - but would it not have been easier to ask a new question? Your original question _has_ been answered, your NullPointerException is a "new problem". – Amos M. Carpenter Nov 07 '11 at 07:58
  • 1
    I understood what you have said. I want to ensure that the API specified you and pankaj is suit for android. So that I posted that null pointer exception issue here. I am accepting pankaj's answer because it contain more documentation, and I am going to up vote your answer. If I can solve that issue later, I will post that solution here. Thanks for spending your valuable time for me. – Sandeep Kumar P K Nov 07 '11 at 13:44
1

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();
        }
    }
pruthwiraj.kadam
  • 1,033
  • 10
  • 11
0

You can just use android worksheet library.

Add this in your gradle implementation 'com.github.elirehema:worksheet:0.0.1'

Implement in your activity class ass

public class MainActivity extends AppCompatActivity {
private WorkSheet workSheet;
private Button button;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = findViewById(R.id.create_excel_sheet);
    final String path  = "ExternalFilePath";
    
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                workSheet = new WorkSheet.Builder(getApplicationContext(), path)
                        .setSheet(List<Object>)
                        .writeSheet();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });


}}

Read More

eli
  • 8,571
  • 4
  • 30
  • 40