阅读.xlsx文件android的内容

时间:2017-10-03 08:08:47

标签: android excel

我是Android的新手。我正在尝试在我的Android应用程序中阅读.xlsx文件的内容。

从设备内部存储或外部存储中挑选文件,或从云中获取文件。

我不知道如何实现这一目标。

当我试图读取时,

下面的代码 InputStream stream = getResources().openRawResource(R.raw.test);

工作正常..可以读取它..但尝试使用文件路径时

public class MainActivity extends Activity {
EditText output;
Button btn_p;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    output = (EditText) findViewById(R.id.textOut);

    btn_p = (Button) findViewById(R.id.btn_p);

    btn_p.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            startActivityForResult(intent, 7);
        }
    });}  @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub

    switch(requestCode){

        case 7:

            if(resultCode==RESULT_OK)
            {

                String PathHolder = data.getData().getPath();

                Toast.makeText(MainActivity.this, PathHolder , Toast.LENGTH_LONG).show();

                onReadClick(PathHolder);

            }
            break;

    }
}

public void onReadClick(String filepath)
{
    printlnToUser("reading XLSX file from resources");

    File inputfile=new File(filepath);/*line to be commented*/

    //below line should uncomment
    //InputStream stream = getResources().openRawResource(R.raw.test);

    try
    {

        InputStream stream=new FileInputStream(inputfile);/*line to be commented*/

        XSSFWorkbook workbook = new XSSFWorkbook(stream);

        XSSFSheet sheet = workbook.getSheetAt(0);
        int rowsCount = sheet.getPhysicalNumberOfRows();
        FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
        for (int r = 0; r<rowsCount; r++) {
            Row row = sheet.getRow(r);
            int cellsCount = row.getPhysicalNumberOfCells();
            for (int c = 0; c<cellsCount; c++) {
                String value = getCellAsString(row, c, formulaEvaluator);
                String cellInfo = "r:"+r+"; c:"+c+"; v:"+value;
                printlnToUser(cellInfo);
            }
        }
    } catch (Exception e)
    {
        /* proper exception handling to be here */
        printlnToUser(e.toString());
    }
}



protected String getCellAsString(Row row, int c, FormulaEvaluator formulaEvaluator) {
    String value = "";
    try {
        Cell cell = row.getCell(c);
        CellValue cellValue = formulaEvaluator.evaluate(cell);
        switch (cellValue.getCellType()) {
            case Cell.CELL_TYPE_BOOLEAN:
                value = ""+cellValue.getBooleanValue();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                double numericValue = cellValue.getNumberValue();
                if(HSSFDateUtil.isCellDateFormatted(cell)) {
                    double date = cellValue.getNumberValue();
                    SimpleDateFormat formatter =
                            new SimpleDateFormat("dd/MM/yyyy");
                    value = formatter.format(HSSFDateUtil.getJavaDate(date));
                } else {
                    value = ""+numericValue;
                }
                break;
            case Cell.CELL_TYPE_STRING:
                value = ""+cellValue.getStringValue();
                break;
            default:
        }
    } catch (NullPointerException e) {
        /* proper error handling should be here */
        printlnToUser(e.toString());
    }
    return value;
}

/**
 * print line to the output TextView
 * @param str
 */
private void printlnToUser(String str) {
    final String string = str;
    if (output.length()>8000) {
        CharSequence fullOutput = output.getText();
        fullOutput = fullOutput.subSequence(5000,fullOutput.length());
        output.setText(fullOutput);
        output.setSelection(fullOutput.length());
    }
    output.append(string+"\n");
} }

显示找不到文件的例外。

1 个答案:

答案 0 :(得分:0)

Uri uri = data.getData(); InputStream stream = getContentResolver().openInputStream(uri); XSSFWorkbook workbook = new XSSFWorkbook(stream);

通过使用此代码,我可以解决这个问题。感谢Selvin