这是我为我的数据库生成备份的代码,我为此使用了 apache poi,但是当我执行时它显示了一些错误。
我从 HSSF 工作表开始,创建一个工作表并从我的数据库中添加详细信息,然后将该文件保存在 sd 卡上的特定位置。
HSSFWorkbook backup=new HSSFWorkbook();
HSSFSheet sheet=backup.createSheet("Contact_Backup");
Map<String, Object[]> data = new HashMap<String, Object[]>();
sq = md.getReadableDatabase();
Cursor mCursor = sq.rawQuery("SELECT * FROM "
+ MyDatabase.TABLE_NAME, null);
if (mCursor.moveToFirst()) {
do {
idbackup.add(mCursor.getString(mCursor.getColumnIndex(MyDatabase.KEY_ID)));
namebackup.add(mCursor.getString(mCursor.getColumnIndex(MyDatabase.KEY_NAME)));
numberbackup.add(mCursor.getString(mCursor.getColumnIndex(MyDatabase.KEY_NUM)));
addressbackup.add(mCursor.getString(mCursor.getColumnIndex(MyDatabase.KEY_ADDR)));
mailbackup.add(mCursor.getString(mCursor.getColumnIndex(MyDatabase.KEY_MAIL)));
} while (mCursor.moveToNext());
}
if (idbackup.size() != 0) {
int j = 2;
for (int i = 0; i < idbackup.size(); i++) {
data.put(String.valueOf(j), new Object[]{idbackup.get(i), namebackup.get(i), numberbackup.get(i), addressbackup.get(i), mailbackup.get(i)});
j++;
}
}
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof Date)
cell.setCellValue((Date) obj);
else if (obj instanceof Boolean)
cell.setCellValue((Boolean) obj);
else if (obj instanceof String)
cell.setCellValue((String) obj);
else if (obj instanceof Double)
cell.setCellValue((Double) obj);
}
}
try {
File directory = new File("/sdcard/BulkMessenger/backups"); /*creating the file directory
directory.mkdir();
long date = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM MM dd, yyyy h:mm a");
String dateString = sdf.format(date);
File file = new File(directory, dateString+"backupcontact.xls");
FileOutputStream out = new FileOutputStream(file);
backup.write(out);
out.close();
Toast.makeText(getApplicationContext(),"Successfully backup generated in backup",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
我的错误日志在下面给出了我得到的 filenotfound 异常。
07-08 09:52:38.250 15615-15615/com.example.web03.bulkmessenger E/dalvikvm: Could not find class 'java.awt.font.FontRenderContext', referenced from method org.apache.poi.hssf.usermodel.HSSFSheet.autoSizeColumn
提前感谢您的帮助!