如何使用apache poi更新excel表中的新行

时间:2013-11-21 15:02:33

标签: android apache-poi

你好朋友我使用apache poi库使用excel文件时遇到问题。这里成功创建了excel文件,但第二次更新此文件时没有任何反应。 请在下方查看我创建或更新文件的代码

public class MainActivity extends Activity implements OnClickListener{
Button writeExcelButton,readExcelButton;
static String TAG = "ExelLog";
static HSSFWorkbook wb = new HSSFWorkbook();
  static HSSFSheet mySheet;
static EditText name,mail,batch,phoneno;
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    name=(EditText)findViewById(R.id.name);
    mail=(EditText)findViewById(R.id.email);
    batch=(EditText)findViewById(R.id.batch);
    phoneno=(EditText)findViewById(R.id.phoneno);

    writeExcelButton = (Button) findViewById(R.id.writeExcel);
    writeExcelButton.setOnClickListener(this);
    readExcelButton = (Button) findViewById(R.id.readExcel);
    readExcelButton.setOnClickListener(this);

}


private static boolean  saveExcelFile(Context context, String fileName) {
    // TODO Auto-generated method stub
     if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) { 
            Log.e(TAG, "Storage not available or read only"); 
            return false; 
        } 

        boolean success = false; 
        try{
            // Creating Input Stream 
            File file = new File(context.getExternalFilesDir(null), fileName); 
            FileInputStream myInput = new FileInputStream(file);

            // Create a POIFSFileSystem object 
            POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

            // Create a workbook using the File System 
            HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

            // Get the first sheet from workbook 
          mySheet = myWorkBook.getSheetAt(0);


        }catch (Exception e){e.printStackTrace(); }
        Cell c = null;

        if(mySheet==null)
        {

        mySheet = wb.createSheet("Student Info");

        // Generate column headings

        Row row = mySheet.createRow(0);

        c = row.createCell(0);
        c.setCellValue("Name");


        c = row.createCell(1);
        c.setCellValue("Batch");


        c = row.createCell(2);
        c.setCellValue("Email");


        c = row.createCell(3);
        c.setCellValue("PhoneNo");




       }
        else
        {
      studentDetial1(mySheet,c);
        }
        // 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);
         //   wb.notify();

            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)
                    wb.notify();
                    os.close(); 
            } catch (Exception ex) { 
            } 
        } 
        return success; 
    } 

    private static void studentDetial1(HSSFSheet mySheet2, Cell c2) {
    // TODO Auto-generated method stub
        int lastIndex=mySheet2.getLastRowNum();
        int i=lastIndex+1;

        Row row = mySheet2.createRow(i);

        c2 = row.createCell(0);
        c2.setCellValue(name.getText().toString());


        c2 = row.createCell(1);
        c2.setCellValue(( batch.getText().toString()));


        c2 = row.createCell(2);
        c2.setCellValue(mail.getText().toString());
      //  c.setCellStyle(cs);

        c2 = row.createCell(3);
        c2.setCellValue(phoneno.getText().toString());


}
private static void readExcelFile(Context context, String filename) { 

    if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) 
    { 
        Log.e(TAG, "Storage not available or read only"); 
        return; 
    } 
    List cellDataList = new ArrayList();
    try{
        // Creating Input Stream 
        File file = new File(context.getExternalFilesDir(null), filename); 
        FileInputStream myInput = new FileInputStream(file);

        // Create a POIFSFileSystem object 
        POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

        // Create a workbook using the File System 
        HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

        // Get the first sheet from workbook 
        HSSFSheet mySheet = myWorkBook.getSheetAt(0);

        /** We now need something to iterate through the cells.**/
        Iterator rowIter = mySheet.rowIterator();

        while(rowIter.hasNext()){
            HSSFRow myRow = (HSSFRow) rowIter.next();
            Iterator cellIter = myRow.cellIterator();
            List cellTempList = new ArrayList();
            while(cellIter.hasNext()){
                HSSFCell myCell = (HSSFCell) cellIter.next();
                cellTempList.add(myCell);
                Log.d(TAG, "Cell Value: " +  myCell.toString());
               Toast.makeText(context, "cell Value: " + myCell.toString(), Toast.LENGTH_SHORT).show();
            }
            cellDataList.add(cellTempList);
        }
    }catch (Exception e){e.printStackTrace(); }
    printToConsole(cellDataList);
    return;
} 

private static void printToConsole(List cellDataList) {
    // TODO Auto-generated method stub
    for (int i = 0; i < cellDataList.size(); i++) {
        List cellTempList = (List) cellDataList.get(i);

        if(cellTempList.get(2).toString().equalsIgnoreCase("mca"))


        {
        for (int j = 0; j < cellTempList.size(); j++) {

            HSSFCell hssfCell = (HSSFCell) cellTempList.get(j);
            String stringCellValue = hssfCell.toString();
        //    Toast.makeText(getBaseContext(), "cell Value: " + hssfCell.toString(), Toast.LENGTH_SHORT).show();
            Log.d("mca", "Cell Value: " +  hssfCell.toString());
            System.out.print(stringCellValue + "\t");
        }
        }
        else { 
        // i++;
        }
        System.out.println();
    }
}




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; 
}

public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) 
    {
    case R.id.writeExcel:
        saveExcelFile(this,"myExcel.xls");
        break;
    case R.id.readExcel:    
        readExcelFile(this,"myExcel.xls");
        break;   
    }

}

}

0 个答案:

没有答案