Android导出Excel

Posted 风水月

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android导出Excel相关的知识,希望对你有一定的参考价值。

最近需要做一个将手机中保存的JSON文件转换成容易阅读的Excel文件,故做了一个小demo,现将该demo用到的一些部件记录一下。

1.文件浏览器

为了方便找到所需的JSON文件,故现做了一个简易的文件浏览器。

1.1文件列表

文件列表采用的是android的空间ListView进行展示的,下面简要对ListView做一个简单的概述。

ListView的创建需要个元素:

1ListView中的每一列的View

2)填入View的数据或者图片等。

3)连接数据与ListView的适配器(Adapter)。

常用的ListView适配器有:ArrayAdapter<T>、SimpleAdatper、SimpleCursorAdapter、BaseAdapter。ArrayAdapter最为简单,ListView每一行只能展示一行字。SimpleAdapter有最好的扩充性,可以自定义出各种效果。SimpleCursorAdapter可以认为是SimpleAdapter对数据库的简单结合,可以方面的把数据库的内容以列表的形式展示出来。BaseAdapter是自定义适配器,使用它必须自定义类继承它,它可以实现更加多样的效果。

下面对ListView的使用做一个简单的描述:

(1)ListView资源视图的定义

<ListView
            android:id="@+id/file_path_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:headerDividersEnabled="true"
            android:footerDividersEnabled="true" android:fastScrollEnabled="true"/>
(2)ListView在Activity中创建

private ListView mListView = null;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mListView = (ListView)findViewById(R.id.file_path_list);
}

(3)各种Adapter的使用

(3.1)ArrayAdatper<T>使用

ArrayAdapter使用的资源视图 R.layout.simple_text.xml的定义

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="5dip"
    android:paddingBottom="5dip"
    android:orientation="horizontal"
    android:gravity="center_vertical">

	<TextView
		android:id="@+id/file_name"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:singleLine="true"
		android:textAppearance="?android:attr/textAppearanceMedium" />
     
</LinearLayout>
ArrayAdapter的使用

List<String> data = new ArrayList<String>();
data.add("数据1");
data.add("数据2");

mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_item,getData()));</span>

 (3.2)SimpleAdapter、SimpleCursorAdapter使用 

SimpleAdatper、SimpleCursorAdapter的使用步骤与ArrayAdapter是一样的,也是需要先定义好需要展示的View的xml,然后创建该Adapter的时候讲该xml的资源ID带人,同时填入数据,下面简单列一下SimpleCursorAdapter读取通讯录用于View展示的代码。

//读取通讯录
Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
startManagingCursor(cursor);
ListAdapter listAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_expandable_list_item_1, cursor,new String[]{People.NAME}, new int[]{android.R.id.text1}); 
mListView.setAdapter(listAdapter);

 (3.3)BaseAdapter的使用 

本次做的读取手机内存卡的文件浏览器采用的就是该适配器,现将代码贴在此:

文件列表每一项样式定义的xml文件:file_browser_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="5dip"
    android:paddingBottom="5dip"
    android:orientation="horizontal"
    android:gravity="center_vertical">

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:gravity="center">
        <ImageView
            android:id="@+id/file_image_frame"
            android:layout_width="65px"
            android:layout_height="65px"
            android:scaleType="centerInside"
            android:gravity="center"
            android:background="@drawable/image_icon_bg"
            android:layout_gravity="center"
            android:visibility="gone" />
        <ImageView
            android:id="@+id/file_image"
            android:layout_width="59px"
            android:layout_height="59px"
            android:scaleType="centerInside"
            android:gravity="center"
            android:layout_gravity="center" />
    </FrameLayout>
    <LinearLayout
        android:id="@+id/file_info_layout"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center_vertical"
        android:orientation="vertical"
        android:paddingLeft="5dip">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/file_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:textAppearance="?android:attr/textAppearanceMedium" />
            <TextView
                android:id="@+id/file_count"
                android:layout_width="wrap_content"
                android:layout_marginLeft="5dip"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:textAppearance="?android:attr/textAppearanceSmall" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/modified_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:gravity="left"
                android:textAppearance="?android:attr/textAppearanceSmall" />
            <TextView
                android:id="@+id/file_size"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:layout_marginLeft="14px"
                android:gravity="left"
                android:textAppearance="?android:attr/textAppearanceSmall" />

        </LinearLayout>
    </LinearLayout>

    <FrameLayout
        android:id="@+id/file_checkbox_area"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:paddingLeft="10dip">

        <ImageView
            android:id="@+id/file_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="fitCenter"
            android:gravity="center"
            android:layout_gravity="center" />

    </FrameLayout>

</LinearLayout>
继承自BaseAdapter的类定义:

package com.szx.exportexcel;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.szx.util.Constant;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class FileListAdapter extends BaseAdapter  {
	private Context mcontext = null;
	private List<File> mfiles = null;
	
	public FileListAdapter(Context context,List<File> files){
		mcontext = context;
		mfiles = files;
	}
	
	@Override
	public int getCount() {
		int count = 0;
		if(mfiles!=null){
			count = mfiles.size();
		}
		return count;
	}

	@Override
	public Object getItem(int position) {
		if((position >= 0) && (position < this.getCount()))
			return mfiles.get(position);	
		return null;
	}

	@Override
	public long getItemId(int position) {
		
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ListHolder mListHolder = null;
		if(convertView==null){
			convertView=LayoutInflater.from(mcontext).inflate(R.layout.file_browser_item, parent,false);
			mListHolder = new ListHolder();
			mListHolder.mfileIcon = (ImageView)convertView.findViewById(R.id.file_image);
			mListHolder.mfileName = (TextView)convertView.findViewById(R.id.file_name);
			mListHolder.mfileSize = (TextView)convertView.findViewById(R.id.file_size);
			mListHolder.mfileTime = (TextView)convertView.findViewById(R.id.modified_time);
			convertView.setTag(mListHolder);
		}else{
			mListHolder = (ListHolder)convertView.getTag();
		}
		
		File f = (File)this.getItem(position);
		if(f!=null){
			String fileIcon = Constant.getFileIcon(f);
			if(fileIcon == null){
				Drawable drawable = this.getApkIcon(f.getAbsolutePath());
				if(drawable!=null){
					mListHolder.mfileIcon.setImageDrawable(drawable);
				}else{
					mListHolder.mfileIcon.setImageResource(R.drawable.file_icon_default);
				}
				
			}else{
				Resources res = mcontext.getResources();
				int icon = res.getIdentifier(fileIcon, "drawable", mcontext.getPackageName());
				if(icon<=0){
					icon = R.drawable.file_icon_default;
				}
				mListHolder.mfileIcon.setImageResource(icon);
			}
			
			if(f.isFile()){
				mListHolder.mfileName.setText(f.getName());
				mListHolder.mfileSize.setText(this.getFileSize(f.length()));
			}else{
				File[] files = f.listFiles();
				mListHolder.mfileSize.setText("");
				if(files!=null){
					mListHolder.mfileName.setText(f.getName()+"("+files.length+")");
				}else{
					mListHolder.mfileName.setText(f.getName());
				}
				
			}
			mListHolder.mfileTime.setText(this.getFileTime(f.lastModified()));
		}
		return convertView;
	}
	
	public String getFileTime(long filetime) {
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss"); 
		String ftime =  formatter.format(new Date(filetime)); 
		return ftime;
	}
	public Drawable getApkIcon(String path){      
		PackageManager pm = mcontext.getPackageManager();      
		PackageInfo info = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);      
		if(info != null){      
			ApplicationInfo appInfo = info.applicationInfo;

			if(Build.VERSION.SDK_INT >= 8){
				appInfo.sourceDir = path;
				appInfo.publicSourceDir = path;
			}

			return appInfo.loadIcon(pm);
		}   		
		return null;
	}
	
	public String getFileSize(long filesize) {
		DecimalFormat df = new DecimalFormat("#.00");
		StringBuffer mstrbuf = new StringBuffer();

		if (filesize < 1024) {
			mstrbuf.append(filesize);
			mstrbuf.append(" B");
		} else if (filesize < 1048576) {
			mstrbuf.append(df.format((double)filesize / 1024));
			mstrbuf.append(" K");			
		} else if (filesize < 1073741824) {
			mstrbuf.append(df.format((double)filesize / 1048576));
			mstrbuf.append(" M");			
		} else {
			mstrbuf.append(df.format((double)filesize / 1073741824));
			mstrbuf.append(" G");
		}

		df = null;

		return mstrbuf.toString();
	}
	
	static class ListHolder{
		ImageView mfileIcon;
		TextView mfileName;
		TextView mfileSize;
		TextView mfileTime;
	}
}
自定义FileListAdapter的使用:

mFileListAdapter = new FileListAdapter(this,mFileList);
mListView.setAdapter(mFileListAdapter);
mFileListAdapter.notifyDataSetChanged();
继承自BaseAdapter的类必须实现如下几个函数:

@Override
public int getCount() {
	// TODO Auto-generated method stub
	return 0;
}

@Override
public Object getItem(int position) {
	// TODO Auto-generated method stub
	return null;
}

@Override
public long getItemId(int position) {
	// TODO Auto-generated method stub
	return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
	// TODO Auto-generated method stub
	return null;
}
其中getCount返回Adapter中有几条数据,getItem返回列表中位置为position的那一项,getView实现了整个列表中每一条样式的展现。

本demo的文件列表展示效果如下:


1.2ListView长按菜单的实现

ListView中长按菜单的实现由两种方式,一种是实现setOnItemLongClickListener事件,另外一种是通过上下文菜单实现。

(1)使用setOnItemLongClickListener实现

使用该方式实现需要自己实现弹出框的代码,本demo中采用上下文菜单方式实现。

mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View v,
			int pos, long id) {
		
		return false;
	}
});
(2)通过上下文菜单实现

(2.1)在OnCreate函数中给ListView注册上下文

registerForContextMenu(mListView);
(2.2)Activity实现onCreateContextMenu、onContextItemSelected两个方法
public void onCreateContextMenu(ContextMenu menu, View v,
		ContextMenuInfo menuInfo) {
	super.onCreateContextMenu(menu, v, menuInfo);
	MenuInflater inflater = getMenuInflater();
	inflater.inflate(R.menu.context_filemenu, menu);
	AdapterView.AdapterContextMenuInfo info = null;

	try {
		info = (AdapterView.AdapterContextMenuInfo) menuInfo;
	} catch (ClassCastException e) {
		return;
	}

	File mselectedFile = (File)mFileListAdapter.getItem(info.position);
	if(mselectedFile != null)
	{
		menu.setHeaderTitle(mselectedFile.getName());
	}
}


public boolean onContextItemSelected(MenuItem item) {
	AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
	File f = (File)mFileListAdapter.getItem(info.position);
	if(f == null)
		return false;
	switch(item.getItemId()){
	case R.id.exportExcel:
		
		return true;
	default:
		return super.onContextItemSelected(item);				
	}    	
}

1.3SD卡路径文件的获取

(1)SD卡路径的获取

File f = null; 
boolean sdCardExist = Environment.getExternalStorageState()   
		.equals(Environment.MEDIA_MOUNTED);   //判断sd卡是否存在 
if   (sdCardExist)   
{                               
	f = Environment.getExternalStorageDirectory();//获取sd卡目录 
	if (f != null) {
		mSDCardPath = f.getAbsolutePath();
	}

	f = Environment.getRootDirectory();//获取根目录 
	if (f != null) {
		mRootPath = f.getAbsolutePath();
	}       
}
(2)SD卡文件的获取及展示

File file = null;
if(mCurrentPathFile!=null){
	if(mCurrentPathFile.isDirectory()){
		file = mCurrentPathFile;
	}else{
		file = mCurrentPathFile.getParentFile();
	}
}else{
	file = new File(mSDCardPath);
}
if(file!=null){
	if(file.exists()&&file.canRead()){
		if(file.isFile()){
			
		}else{
			mFileList.clear();
			mFileListAdapter.notifyDataSetChanged();
			mCurrentPathFile = file;
			mCurrentPathView.setText(mCurrentPathFile.getAbsolutePath());
			File[] files = file.listFiles();
			Arrays.sort(files,new FileComparator());
			for(File f:files){
				mFileList.add(f);
				mFileListAdapter.notifyDataSetChanged();
			}
		}
	}
}


2.JSON字符串转换成HashMap

JSON解析的库有三种:Android自带的JSON解析库,net.sf.json库,gson库。其中Android自带的JSON库使用起来不方便,net.sf.json库使用的Jar包与Android的包冲突,故Android中普遍使用gson来进行JSON的解析。

下面是从网上摘录的使用gson转换JSON串为Map的工具类

package com.szx.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * 使用Gson把json字符串转成Map
 */
public class JSONUtil {
	
	/**
	 * 获取JsonObject
	 * @param json
	 * @return
	 */
	public static JsonObject parseJson(String json){
		JsonParser parser = new JsonParser();
	    JsonObject jsonObj = parser.parse(json).getAsJsonObject();
		return jsonObj;
	}
	
	/**
	 * 根据json字符串返回Map对象
	 * @param json
	 * @return
	 */
	public static Map<String,Object> toMap(String json){
		return JSONUtil.toMap(JSONUtil.parseJson(json));
	}
	
	/**
	 * 将JSONObjec对象转换成Map-List集合
	 * @param json
	 * @return
	 */
	public static Map<String, Object> toMap(JsonObject json){
	    Map<String, Object> map = new HashMap<String, Object>();
	    Set<Entry<String, JsonElement>> entrySet = json.entrySet();
	    for (Iterator<Entry<String, JsonElement>> iter = entrySet.iterator(); iter.hasNext(); ){
	    	Entry<String, JsonElement> entry = iter.next();
	    	String key = entry.getKey();
	    	Object value = entry.getValue();
	        if(value instanceof JsonArray)
	            map.put((String) key, toList((JsonArray) value));
	        else if(value instanceof JsonObject)
	            map.put((String) key, toMap((JsonObject) value));
	        else
	            map.put((String) key, value);
	    }
	    return map;
	}
	
	/**
	 * 将JSONArray对象转换成List集合
	 * @param json
	 * @return
	 */
	public static List<Object> toList(JsonArray json){
	    List<Object> list = new ArrayList<Object>();
	    for (int i=0; i<json.size(); i++){
	    	Object value = json.get(i);
	    	if(value instanceof JsonArray){
	            list.add(toList((JsonArray) value));
	    	}
	        else if(value instanceof JsonObject){
	            list.add(toMap((JsonObject) value));
	        }
	        else{
	            list.add(value);
	        }
	    }
	    return list;
	}

}

虽然net.sf.json与Android冲突,但是使用它转JSON串的工具类在其他地方用处也很大,故也记录与此。

net.sf.json使用的jar文件如图:



工具类如下:

package com.szx.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import android.content.Context;

public class JSONUtil {

	public static String getRaw(Context context, int RawId) {

		try {
			InputStream is = context.getResources().openRawResource(RawId);
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			// StringBuffer线程安全;StringBuilder线程不安全
			StringBuffer sb = new StringBuffer();
			for (String str = null; (str = reader.readLine()) != null;) {
				sb.append(str);
			}
			return sb.toString();

		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getAsset(Context context, String fileName) {

		try {
			InputStream is = context.getResources().getAssets().open(fileName);
			// StringBuffer线程安全;StringBuilder线程不安全
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			StringBuffer sb = new StringBuffer();
			for (String str = null; (str = reader.readLine()) != null;) {
				sb.append(str);
			}
			return sb.toString();

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

		return null;
	}

	public static void JsonObject2HashMap(JSONObject jo, List<Map<?, ?>> rstList) {
		for (Iterator<String> keys = jo.keys(); keys.hasNext();) {
			try {
				String key1 = keys.next();
				System.out.println("key1---" + key1 + "------" + jo.get(key1)
						+ (jo.get(key1) instanceof JSONObject) + jo.get(key1)
						+ (jo.get(key1) instanceof JSONArray));
				if (jo.get(key1) instanceof JSONObject) {

					JsonObject2HashMap((JSONObject) jo.get(key1), rstList);
					continue;
				}
				if (jo.get(key1) instanceof JSONArray) {
					JsonArray2HashMap((JSONArray) jo.get(key1), rstList);
					continue;
				}
				System.out.println("key1:" + key1 + "----------jo.get(key1):"
						+ jo.get(key1));
				json2HashMap(key1, jo.get(key1), rstList);

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

		}

	}
	public static void JsonArray2HashMap(JSONArray joArr,
			List<Map<?, ?>> rstList) {
		for (int i = 0; i < joArr.size(); i++) {
			try {
				if (joArr.get(i) instanceof JSONObject) {

					JsonObject2HashMap((JSONObject) joArr.get(i), rstList);
					continue;
				}
				if (joArr.get(i) instanceof JSONArray) {

					JsonArray2HashMap((JSONArray) joArr.get(i), rstList);
					continue;
				}
				System.out.println("Excepton~~~~~");

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

		}

	}

	public static void json2HashMap(String key, Object value,
			List<Map<?, ?>> rstList) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put(key, value);
		rstList.add(map);
	}
	
	/**
	 * @param jsonData
	 * @param rstList
	 * @param params
	 * @func hashmap追加字段
	 */
	public static void JsonToHashMap(JSONObject jsonData, Map<String, Object> rstList,
			String... params) {
		try {
			for (Iterator<String> keyStr = jsonData.keys(); keyStr.hasNext();) {

				String key1 = keyStr.next().trim();
				if (jsonData.get(key1) instanceof JSONObject) {
					HashMap<String, Object> mapObj = new HashMap<String, Object>();
					JsonToHashMap((JSONObject) jsonData.get(key1), mapObj, params);
					rstList.put(key1, mapObj);
					continue;
				}
				if (jsonData.get(key1) instanceof JSONArray) {
					ArrayList<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();

					JsonToHashMap((JSONArray) jsonData.get(key1), arrayList, params);
					rstList.put(key1, arrayList);
					continue;
				}
				JsonToHashMap(key1, jsonData.get(key1), rstList);
			}
			// 追加字段
			if (params != null && params.length == 2) {
				rstList.put(params[0], params[1]);
			}
			if (params != null && params.length == 4) {
				rstList.put(params[0], params[1]);
				rstList.put(params[2], params[3]);
			}

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

	}

	public static void JsonToHashMap(JSONArray jsonarray, List<Map<String, Object>> rstList,
			String... params) {
		try {
			for (int i = 0; i < jsonarray.size(); i++) {
				if (jsonarray.get(i) instanceof JSONObject) {

					HashMap<String, Object> mapObj = new HashMap<String, Object>();
					JsonToHashMap((JSONObject) jsonarray.get(i), mapObj, params);
					rstList.add(mapObj);
					continue;
				}
			}

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

	}

	public static void JsonToHashMap(String key, Object value, Map<String, Object> rstList) {
		key = replaceBlank(key);
		if (value instanceof String) {
			rstList.put(key, replaceBlank((String) value));
			return;
		}
		rstList.put(key, value);
	}
	
	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\\\s*|t|r|n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}
}


3.导出Excel

Android中导出excel使用的类库是jxl,下面是使用jxl.jar实现的导出excel的类

package com.szx.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class ExcelUtils {
	public static WritableFont arial14font = null;

	public static WritableCellFormat arial14format = null;
	public static WritableFont arial10font = null;
	public static WritableCellFormat arial10format = null;
	public static WritableFont arial12font = null;
	public static WritableCellFormat arial12format = null;

	public final static String UTF8_ENCODING = "UTF-8";
	public final static String GBK_ENCODING = "GBK";

	public static void format() {
		try {
			arial14font = new WritableFont(WritableFont.ARIAL, 14,
					WritableFont.BOLD);
			arial14font.setColour(jxl.format.Colour.LIGHT_BLUE);
			arial14format = new WritableCellFormat(arial14font);
			arial14format.setAlignment(jxl.format.Alignment.CENTRE);
			arial14format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
			arial14format.setBorder(jxl.format.Border.ALL,
					jxl.format.BorderLineStyle.THIN);
			arial14format.setBackground(jxl.format.Colour.VERY_LIGHT_YELLOW);
			arial10font = new WritableFont(WritableFont.ARIAL, 10,
					WritableFont.BOLD);
			arial10format = new WritableCellFormat(arial10font);
			arial10format.setAlignment(jxl.format.Alignment.CENTRE);
			arial10format.setBorder(jxl.format.Border.ALL,
					jxl.format.BorderLineStyle.THIN);
			arial10format.setBackground(jxl.format.Colour.LIGHT_BLUE);
			arial12font = new WritableFont(WritableFont.ARIAL, 12);
			arial12format = new WritableCellFormat(arial12font);
			arial12format.setBorder(jxl.format.Border.ALL,
					jxl.format.BorderLineStyle.THIN);
		} catch (WriteException e) {

			e.printStackTrace();
		}
	}
	public static void createSmtrautExcel(String fileName,String sheetName,String[] lineName,String[] colName,List<List<Map<String,Object>>>values){
		format();
		WritableWorkbook workbook = null;
		try {
			File file = new File(fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
			boolean isWrite = file.canWrite();
			workbook = Workbook.createWorkbook(file);
			WritableSheet sheet = workbook.createSheet(sheetName, 0);
			int ran = 1;
			for(int j=0;j<values.size();j++){
				sheet.setRowView(j*6+ran-1, 600);
				for (int line = 0; line < lineName.length; line++) {
					sheet.addCell(new Label(line+1, j*6+ran, lineName[line], arial10format));
				}
				for (int col = 0; col < colName.length; col++) {
					sheet.addCell(new Label(0, col+j*6+ran+1, colName[col], arial10format));
				}
				
				for(int i=0;i<values.get(j).size();i++){
					Map<String,Object> m = values.get(j).get(i);
					int col = (Integer) m.get("col");
					int line = (Integer)m.get("line");
					String value = (String)m.get("value");
					if(col==0&&line==0){
						sheet.addCell(new Label(col,line+j*6+ran-1, value, arial14format));
						sheet.addCell(new Label(col,line+j*6+ran, "", arial10format));
						sheet.mergeCells(col, line+j*6+ran-1, col+lineName.length, line+j*6+ran-1);
					}else{
						sheet.addCell(new Label(col,line+j*6+ran, value, arial10format));
					}
				}
				ran++;
			}
			workbook.write();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (workbook != null) {
				try {
					workbook.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

使用jxl进行导出excel导出文件,简单说几点:

(1)创建excel:WritableWorkbook workbook = Workbook.createWorkbook(file);

(2)创建sheet:WritableSheet sheet = workbook.createSheet(sheetName, 0);

(3)写入单元格数据:sheet.addCell(new Label(col,line+j*6+ran, value, arial10format));其中Label中第一个参数是列,第二个参数是行,第三个参数是写入单元格中的值,第四个参数是单元格的样式

(4)设置行高:sheet.setRowView(j*6+ran-1, 600);其中第一个参数是行号,第二个参数是行高

(5)合并单元格:sheet.mergeCells(col, line+j*6+ran-1, col+lineName.length, line+j*6+ran-1);其中第一个参数是合并单元格左上角的列号,第二个参数是左上角的行号,第三个参数是右下角的列号,第四个参数是右下角的行号。


上述即是该demo中使用的技术点,该demo可从该处下载

该demo实现了如下JSON串:

{"acc_ffz":1.6,"acc_fz":0.8,"acc_yxz":0.6,"bulk_mathValue":-1.0,"dis_ffz":10.8,"dis_fz":5.4,"dis_yxz":3.8,"en_ffz":1.4,"en_fz":0.7,"en_yxz":0.5,"sample_time":"2016-09-09T03:15:25.313+0000","signalType":-1,"tmp":41.2,"vel_ffz":1.1,"vel_fz":0.6,"vel_yxz":0.4}
转换成该改格式的excel表:












以上是关于Android导出Excel的主要内容,如果未能解决你的问题,请参考以下文章

Android导出Excel表格文件

Android导出Excel

binbinyang博客----关于Android数据库导出到Excel

phpExcel 操作示例

Android国际化翻译多国String导入导出(EXCEL)实现

Android国际化翻译多国String导入导出(EXCEL)实现