/**此处导出的是电话联系人*/
1、导入poijar包;
2、可能会报出异常:
如何解决error:execution failed for task app:transformclasseswithjarmerging
解决方法:
defaultConfig {
multiDexEnabled true
}
3代码如下
public class backUpUtils {
public interface backUpCallBack{
public void onCallBack(int progress);
public void befor(int count);
}
public static boolean backUp(Context context, backUpCallBack callBack){
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//判断是否有sdk
File file=new File(Environment.getExternalStorageDirectory(),"workbook.xls");//建立sms文件
ContentResolver resolver = context.getContentResolver();
//Uri uri = Uri.parse("content://sms/");
Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, null, null, null);//遍历数据表
int count=cursor.getCount();
callBack.befor(count);
int progress=0;
try {
OutputStream os=new FileOutputStream(file);
// XmlSerializer serializer= Xml.newSerializer();//序列化数据
// serializer.setOutput(os,"utf-8");
// serializer.startDocument("utf-8",true);
// serializer.startTag(null,"contact");
HSSFWorkbook wb=new HSSFWorkbook();
HSSFSheet sheet=wb.createSheet("new sheet");
wb.setSheetName(0,"数据库数据");
HSSFRow row=sheet.createRow((short)0);
sheet.createFreezePane(0,1);
cteateCell(wb,row,(short)0,"联系人");
cteateCell(wb,row,(short)1,"电话号码");
int i=0;
while (cursor.moveToNext()) {
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("联系人:"+name+">>>>>>>>"+"电话号码"+number);
i++;
HSSFRow row2=sheet.createRow((short)i);
cteateCell(wb,row2,(short)0,name);
cteateCell(wb,row2,(short)1,number);
progress++;
callBack.onCallBack(progress);
SystemClock.sleep(200);
}
wb.write(os);//写入流
os.flush();
os.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
private static void cteateCell(HSSFWorkbook wb, HSSFRow row, short col, String val)
{
HSSFCell cell=row.createCell(col);
cell.setCellValue(val);
HSSFCellStyle cellstyle=wb.createCellStyle();
cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
cell.setCellStyle(cellstyle);
}
}