我正在尝试使用Android Studio中的Apache POI将数据输入到excel电子表格的下一行。目前,我的应用程序是关于扫描QR码然后基于QR码的值,它将值传输到excel。我设法只插入excel中的第一行。但是,它只是在扫描另一个QR码后用新值替换。所以我需要修改一些代码,以便每次扫描时它都会插入到一个新行中。需要一些指南。
当前代码:
private static boolean saveExcelFile(Context context, String fileName, String result) {
// check if available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.e(TAG, "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("Material_List");
// Generate column headings
Row row = sheet1.createRow(0);
c = row.createCell(0);
c.setCellValue("Material Code");
c.setCellStyle(cs);
c = row.createCell(1);
c.setCellValue("Material Name");
c.setCellStyle(cs);
c = row.createCell(2);
c.setCellValue("Lot Size");
c.setCellStyle(cs);
c = row.createCell(3);
c.setCellValue("Quantity");
c.setCellStyle(cs);
sheet1.setColumnWidth(0, (15 * 500));
sheet1.setColumnWidth(1, (15 * 500));
sheet1.setColumnWidth(2, (15 * 500));
sheet1.setColumnWidth(3, (15 * 500));
//String str = result.getContents();
//String str = "1000000000 SA241ASDAA 1IKSDKE 200";
String str = result;
String[] splited = str.split("\\s+");
String split_one=splited[0];
String split_second=splited[1];
String split_three=splited[2];
String split_four=splited[3];
// Generate column headings
Row row2 = sheet1.createRow(1);
c = row2.createCell(0);
c.setCellValue(split_one);
c = row2.createCell(1);
c.setCellValue(split_second);
c = row2.createCell(2);
c.setCellValue(split_three);
c = row2.createCell(3);
c.setCellValue(split_four);
// Create a path where we will place our List of objects on external storage
File file = new File(context.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;
}