Build excel in Android

Source: Internet
Author: User

All say the programmer unhappy product manager, in fact, sometimes encountered some wonderful background developers will be very uncomfortable. A recent project has a requirement to generate an Excel and then send an email to the customer. Results The background staff directly to the client, the reason is the background is not good to implement. Hearing this can only be achieved by themselves (in minutes you want a spiral King buckle it head). This blog is about creating Excel tables in Android and co-existing to local. Let's look at the following generation:

Initializing data

First we have to build the test data, here I write the data dead in a constant class const, as follows:

 Public classConst { Public Interfaceorderinfo{ Public StaticFinal string[][] Orderone =NewString[][] {{"123","Kowloon","13294352311","Wuhan Sekinoyamaguchi"},{"124","our","13294352312","Fruit Lake in Wuhan"},{" the","Chen Jia","13294352315","Wuhan Chinese Teacher"},{"126","Lee","13294352316","Wuhan Yang Jia Wan"}}; }}

Theoretically, this data is read from the background.
This article simulates the printing of order information, so you need an Order model class:

publicclass Order implements Serializable {    public String id;    public String restPhone;    public String restName;    public String receiverAddr;    publicOrder(String id,String restPhone, String restName, String receiverAddr) {        this.id = id;        this.restPhone = restPhone;        this.restName = restName;        this.receiverAddr = receiverAddr;    }}
Storage Memory Card

Next we want to determine whether the memory card exists, the memory is large enough. Get the size of the memory in the specified directory first:

    /** 获取SD可用容量 */    privatestaticlonggetAvailableStorage(Context context) {        String root = context.getExternalFilesDir(null).getPath();        new StatFs(root);        long blockSize = statFs.getBlockSize();        long availableBlocks = statFs.getAvailableBlocks();        long availableSize = blockSize * availableBlocks;        // Formatter.formatFileSize(context, availableSize);        return availableSize;    }

The path used here is Getexternalfilesdir, which specifies sdcard/android/data/your app's package name/files/directory, which is used for a long time to save the data, when the application is uninstalled, it will be deleted at the same time. There is a Getexternalcachedir method like this, but it is generally used to store temporary files. The size of the usable capacity is then calculated by Statfs.
The memory is then judged before writing to Excel, as follows:

if (! Environment. Getexternalstoragestate(). Equals(Environment. MEDIA_mounted) &&getavailablestorage () >1000000) {Toast. Maketext(Context,"SD card not available", Toast. LENGTH_long). Show();Return;} File File;File dir = new file (context. Getexternalfilesdir(NULL). GetPath());File = new file (dir, FileName +". xls");if (!dir. Exists()) {dir. Mkdirs();}

If the memory card does not exist or the memory is less than 1M, do not write, and then create the appropriate folder and name it. Next, focus on how to write to Excel.

Generate Write to Excel
    • Importing related Packages
      Here we need to import the JXL package, which is mainly for the processing of Excel, this package I will be attached to the project on GitHub, the link will be given later.
    • Build an Excel Worksheet
      The following code generates an Excel table under the specified path, which is an empty table at this point.
WritableWorkbook wwb;        os = new FileOutputStream(file);        wwb = Workbook.createWorkbook(os);
    • Add Sheet Table
      Familiar with Excel operations know that Excel can create a new number of sheet tables. The following code generates the first worksheet with the name "order":
WritableSheet sheet = wwb.createSheet("订单"0);
    • Add an Excel table header
      Add Excel header, here you can customize the style of the header, first look at the code:
"订单""店名""电话""地址" };Label label;        for (int0; i < title.length; i++) {            // Label(x,y,z) 代表单元格的第x+1列,第y+1行, 内容z                        // 在Label对象的子对象中指明单元格的位置和内容            new0, title[i], getHeader());            // 将定义好的单元格添加到工作表中            sheet.addCell(label);        }

Here's the table header information I wrote dead. A table cell corresponds to a label, such as a label (0,0, "a"), which represents the cell information for the first column of the first row as a. GetHeader () is a custom style that returns a Writablecellformat. To see how to customize the style:

public static Writablecellformat GetHeader () {Writablefont font = new Writablefont (writablefont. Times,Ten, Writablefont. BOLD);//define Fonttry {font. Setcolour(Colour. BLUE);//Blue Font} catch (WriteException E1) {E1. Printstacktrace();} writablecellformat format = new Writablecellformat (font);try {format. Setalignment(JXL. Format. Alignment. CENTRE);//center aroundFormat. Setverticalalignment(JXL. Format. VerticalAlignment. CENTRE);//Up and down centerFormat. SetBorder(Border. All, Borderlinestyle. THIN, colour. BLACK);//Black BorderFormat. SetBackground(Colour. YELLOW);//Yellow background} catch (WriteException e) {E. Printstacktrace();} return format;}

Look at the above code is very clear, by obtaining writablefont from the definition of some of the font style, such as color size, through the Writablecellformat to set the text box style, you can set the border background and so on. Specific to the API documentation can be found here, only examples.

    • Add Excel content.
for (int i =0; i < exportorder.size (); i++) {Order order = Exportorder. Get(i);Label Ordernum = new label (0, i +1, order. ID);Label restaurant = new Label (1, i +1, order. Restname);Label Namelabel = new label (2, i+1, order. Restphone);Label address = new label (3, i +1, order. Receiveraddr);Sheet. Addcell(Ordernum);Sheet. Addcell(restaurant);Sheet. Addcell(Namelabel);Sheet. Addcell(address);Toast. Maketext(Context,"Write succeeded", Toast. LENGTH_long). Show();}

This is simple enough to get the order information and write it one by one.

Main class

This demo layout is very simple is a button click to generate Excel, which is not posted here, mainactivity code as follows:

protected void OnCreate (Bundle savedinstancestate) {Super. OnCreate(savedinstancestate);Setcontentview (R. Layout. Activity_main);int length = Const. OrderInfo. Orderone. Length;for (int i =0; i < length;i++) {Order order = New Order (Const. OrderInfo. OrderoneI [0], Const. OrderInfo. OrderoneI [1], Const. OrderInfo. OrderoneI [2], Const. OrderInfo. OrderoneI [3]);Orders. Add(order);} BTN = (Button) Super. Findviewbyid(R. ID. BTN);Btn. Setonclicklistener(New Onclicklistener () {@Override public void OnClick (View v) {//TODO Auto-generat Ed Method stub try {Excelutil. Writeexcel(mainactivity. this, Orders,"Excel_"+new Date (). toString());} catch (Exception e) {//TODO auto-generated catch block E. Printstacktrace();}            }        });}

Here I wrap the code that generates excel above into a tool class Excelutil, which is called directly after use. Mainactivity is to call Excelutil to write the array into order. To this Android implementation of the Excel feature is implemented.
Source Address

Build excel in Android

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.