感谢以下链接
http://www.mysamplecode.com/2011/10/android-read-write-excel-file-using.html
为我工作:)
工作编辑代码:
public static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
public static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean saveExcelFile(MainActivity mainActivity, String fileName) {
// check if available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.w("FileUtils", "Storage not available or read only");
return false;
}
boolean success = false;
//New Workbook
Workbook wb = new HSSFWorkbook();
Cell c = null;
//Cell style for header row
CellStyle cs = wb.createCellStyle();
cs.setFillForegroundColor(HSSFColor.LIME.index);
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//New Sheet
Sheet sheet1 = null;
sheet1 = wb.createSheet("Sheet1");
// Generate column headings
Row row = sheet1.createRow(0);
c = row.createCell(0);
c.setCellValue(DBHelper.INVENTORY_PROJECT_CODE);
c.setCellStyle(cs);
c = row.createCell(1);
c.setCellValue(DBHelper.INVENTORY_PROJECT_UPC_BAR_CODE);
c.setCellStyle(cs);
c = row.createCell(2);
c.setCellValue(DBHelper.INVENTORY_PROJECT_NAME);
c.setCellStyle(cs);
c = row.createCell(3);
c.setCellValue(DBHelper.INVENTORY_PROJECT_QUANTITY);
c.setCellStyle(cs);
c = row.createCell(4);
c.setCellValue(DBHelper.INVENTORY_PROJECT_PRICE);
c.setCellStyle(cs);
ArrayList<String> arrayList1 = dbHelper.getAllRecords();
int rowno = 1;
int columnno=0;
for(String red : arrayList1){
columnno = 0;
Row row1 = sheet1.createRow(rowno);
String[] parts = red.split(Pattern.quote(","));
for(String str : parts){
c = row1.createCell(columnno);
c.setCellValue(str);
c.setCellStyle(cs);
columnno++;
}
rowno++;
}
sheet1.setColumnWidth(0, (15 * 500));
sheet1.setColumnWidth(1, (15 * 500));
sheet1.setColumnWidth(2, (15 * 500));
sheet1.setColumnWidth(3, (15 * 500));
sheet1.setColumnWidth(4, (15 * 500));
// Create a path where we will place our List of objects on external storage
File file = new File(mainActivity.getExternalFilesDir(null), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
return success;
}