android中產生excel

來源:互聯網
上載者:User

android中產生excel

都說程式員不爽產品經理,其實有的時候遇到一些奇葩的後台開發人員也會很不順心。最近項目有這樣一個要求,要產生一個excel然後發郵件給客戶。結果後台人員直接把這個功能扔給用戶端,理由是後台不好實現。聽到這也就只能自己實現了(分分鐘就想來個螺旋王扣它頭上)。這篇部落格講下如下在android中產生excel表並存到本地。先看下產生後的:

初始化資料

首先我們要先造下測試資料,這裡我把資料寫死在一個常量類Const中,如下:

public class Const {    public interface OrderInfo{        public static final String[][] orderOne = new String[][] {{ "123", "九龍", "13294352311",            "武漢市關山口" },{ "124", "咱家", "13294352312",            "武漢市水果湖" },{ "125", "陳家", "13294352315",            "武漢市華師" },{ "126", "李", "13294352316",            "武漢市楊家灣" }};    }}

理論上這些資料是從後台讀過來的。
本文類比列印訂單的資訊,所以這裡還需要一個訂單Model類:

public class Order implements Serializable {    public String id;    public String restPhone;    public String restName;    public String receiverAddr;    public Order(String id,String restPhone, String restName, String receiverAddr) {        this.id = id;        this.restPhone = restPhone;        this.restName = restName;        this.receiverAddr = receiverAddr;    }}
存記憶卡

接下來我們要判斷一下記憶卡是否存在,記憶體是否足夠大。先擷取指定目錄下記憶體的大小:

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

這裡用到的路徑是getExternalFilesDir,它指定的是SDCard/Android/data/你的應用的包名/files/ 目錄這個目錄,它用來放一些長時間儲存的資料,當應用被卸載時,會同時會刪除。類似這種情況的還有getExternalCacheDir方法,只是它一般用來存放臨時檔案。之後通過StatFs來計算出可用容量的大小。
接下來在寫入excel前對記憶體進行判斷,如下:

if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)&&getAvailableStorage()>1000000) {            Toast.makeText(context, "SD卡不可用", 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();        }

如果記憶卡不存在或記憶體小於1M,不進行寫入,然後建立相應的檔案夾並起名字。接下來重點看下如何寫入excel。

產生寫入excel匯入相關包
這裡需要匯入jxl包,它主要就是用於處理excel的,這個包我會附在項目放在github中,後面會給出連結。 產生excel工作表
以下代碼是在指定路徑下產生excel表,此時只是一個空表。
WritableWorkbook wwb;        OutputStream os = new FileOutputStream(file);        wwb = Workbook.createWorkbook(os);
添加sheet表
熟悉excel操作的都知道excel可以建立很多個sheet表。以下代碼產生第一個工作表,名字為“訂單”:
WritableSheet sheet = wwb.createSheet("訂單", 0);
添加excel表頭
添加excel的表頭,這裡可以自訂表格頭的樣式,先看代碼:
String[] title = { "訂單", "店名", "電話", "地址" };Label label;        for (int i = 0; i < title.length; i++) {            // Label(x,y,z) 代表儲存格的第x+1列,第y+1行, 內容z                        // 在Label對象的子物件中指明儲存格的位置和內容            label = new Label(i, 0, title[i], getHeader());            // 將定義好的儲存格添加到工作表中            sheet.addCell(label);        }

這裡表頭資訊我寫死了。表的一個儲存格對應一個Label,如label(0,0,”a”)代表第一行第一列所在的儲存格資訊為a。getHeader()是自訂的樣式,它返回一個 WritableCellFormat 。來看看如何自訂樣式:

    public static WritableCellFormat getHeader() {        WritableFont font = new WritableFont(WritableFont.TIMES, 10,                WritableFont.BOLD);// 定義字型        try {            font.setColour(Colour.BLUE);// 藍色字型        } catch (WriteException e1) {            e1.printStackTrace();        }        WritableCellFormat format = new WritableCellFormat(font);        try {            format.setAlignment(jxl.format.Alignment.CENTRE);// 左右置中            format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 上下置中             format.setBorder(Border.ALL, BorderLineStyle.THIN,             Colour.BLACK);// 黑色邊框             format.setBackground(Colour.YELLOW);// 黃色背景        } catch (WriteException e) {            e.printStackTrace();        }        return format;    }

看上面代碼就很清楚了,通過獲得WritableFont 來自訂字型的一些樣式,如顏色大小等,通過WritableCellFormat 來設定文字框的樣式,可以設定邊框底色等。具體的可以查api文檔,這裡只給出例子。

添加excel內容。
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, "寫入成功", Toast.LENGTH_LONG).show();        }

這就再簡單不過了,就是擷取order資訊然後一個個寫入。

主類

這個demo布局很簡單就是一個按鈕點擊來產生excel,這裡就不貼出來了,MainActivity的代碼如下:

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.orderOne[i][0],  Const.OrderInfo.orderOne[i][1],  Const.OrderInfo.orderOne[i][2],  Const.OrderInfo.orderOne[i][3]);            orders.add(order);        }        btn = (Button)super.findViewById(R.id.btn);        btn.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                // TODO Auto-generated method stub                try {                    ExcelUtil.writeExcel(MainActivity.this,                            orders, "excel_"+new Date().toString());                } catch (Exception e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        });    }

這裡我把上面產生excel的代碼封裝到一個工具類ExcelUtil中,以後使用就直接調用 。MainActivity就是將數組組裝到Order中調用ExcelUtil來寫入。到此android實現excel功能就實現了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.