在android平台如何把数据导入到excel文件中,以便方便查看数据呢?
我知道的方法有三种:
方法1,不借助第3方插件,按照excel中空格键和table键的分布来写文件,把文件后缀名写为.xls;
方法2,借助第三方插件,如一个叫做IPO的插件;
方法3,借助第三方插件,如一个叫作JIX的插件。
昨天本人用的是第三种方法,现在记录下来,以便不时之需:
step1:去网上下载jix.jar包;
step2:导入到工程中。(可以导入到eclipse中,或在源码的package/apps/目录编译。具体方法如我的另一篇博文《.jar文件在android源码中的编译》)
step3:把关键代码贴在这,仅供参考:
import java.io.File;
import java.io.IOException;
import java.util.List;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import android.content.Context;
import android.os.Environment;
import com.sprdsrt.base.core.ResRecord;
public class JxlHelper {
private static final String TAG = "leichi";
private Context mContext = null;
public JxlHelper(Context context) {
mContext = context;
}
public void writeDataToExcel() {
Listlist = ProviderUtil.getResRecordList(mContext);
WritableWorkbook wwb = null;
String fileName = Environment.getExternalStorageDirectory() + "/" + "SrtResult" + ".xls";
int size = list.size();
int numrows = size;
int numcols = 6;
String[][] SrtResult = new String[size + 1][numcols];
// the extra row is used for title;
SrtResult[0][0] = "_ID";
SrtResult[0][1] = "PACKAGENAME";
SrtResult[0][2] = "CASEID";
SrtResult[0][3] = "RESULT";
SrtResult[0][4] = "DESCRIPTION";
SrtResult[0][5] = "NOTE";
for (int i = 0; i < size; i++) {
SrtResult[i + 1][0] = String.valueOf(list.get(i).getId());
SrtResult[i + 1][1] = list.get(i).getPackageName();
SrtResult[i + 1][2] = list.get(i).getCaseID();
SrtResult[i + 1][3] = list.get(i).getResult();
SrtResult[i + 1][4] = list.get(i).getCaseDescription();
SrtResult[i + 1][5] = list.get(i).getNote();
}
try {
wwb = Workbook.createWorkbook(new File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
if (wwb != null) {
// to create a table;
// Workbook的createSheet has two parameters,the first one is the name
// of table,and the second one is the position of this table in a
// book.
WritableSheet ws = wwb.createSheet("sheet1", 0);
// to add the cells
for (int i = 0; i < numrows + 1; i++) {
for (int j = 0; j < numcols; j++) {
// Note:the j means the column,the i means row
Label labelC = new Label(j, i, SrtResult[i][j]);
try {
// add the cells got just now into table;
ws.addCell(labelC);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
}
try {
wwb.write();
wwb.close();
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}