andorid zabawa z plikiem excel -poi

0
private static void readExcelFile(Context context, String filename, String data[][][]) {

    if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
        Log.e(TAG, "Storage not available or read only");
        return;
    }

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

        Toast.makeText(context, "File open", Toast.LENGTH_LONG).show();

        // edit file
        Cell cell = null;
        HSSFRow row;
        for (int i = 0; i < 7; i++) {
            row = mySheet.getRow(i + 5);
            for (int day = 0; day < 7; day++) {
                if (data[0][i][day] != null) {
                    cell = row.getCell(0 + (day * 6));
                    cell.setCellValue(data[0][i][day]);
                }
                if (data[1][i][day] != null) {
                    cell = row.getCell(4 + (day * 6));
                    cell.setCellValue(data[1][i][day]);
                }
                if (data[2][i][day] != null) {
                    cell = row.getCell(5 + (day * 6));
                    cell.setCellValue(data[2][i][day]);
                }
            }
        }

//edit 2
        for (int rowIndex = 2; rowIndex < 4; rowIndex++) {
            row = mySheet.getRow(rowIndex);
            for (int cellDay = 0; cellDay < 5; cellDay++) {
                if (data[rowIndex + 1][0][cellDay] != null) {
                    cell = row.getCell(1 + (cellDay * 6));
                    cell.setCellValue(data[rowIndex + 1][0][cellDay]);
                }
            }
        }
        myInput.close();


        File file2 = new File(context.getExternalFilesDir(null), "Arkusz pracy.xls");
        FileOutputStream os = null;

        try {
            os = new FileOutputStream(file2);
            myWorkBook.write(os);
            Log.w("FileUtils", "Writing file" + file);
            Toast.makeText(context, "File ready ", Toast.LENGTH_SHORT).show();
            os.close();
        } 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) {
            }
        }

    } catch (Exception e) {
        e.printStackTrace();


    }
}

0

Witam chciałem się poradzić bo bawię się z edycja excela przez apkę korzystając z poi, czy to jest w miarę znośny kawałek kodu? zwłaszcza chodzi mi o Stream

private static void readExcelFile(Context context, String filename, String data[][][]) {
 
    if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
        Log.e(TAG, "Storage not available or read only");
        return;
    }
 
    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);
 
        Toast.makeText(context, "File open", Toast.LENGTH_LONG).show();
 
        // edit file
        Cell cell = null;
        HSSFRow row;
        for (int i = 0; i < 7; i++) {
            row = mySheet.getRow(i + 5);
            for (int day = 0; day < 7; day++) {
                if (data[0][i][day] != null) {
                    cell = row.getCell(0 + (day * 6));
                    cell.setCellValue(data[0][i][day]);
                }
                if (data[1][i][day] != null) {
                    cell = row.getCell(4 + (day * 6));
                    cell.setCellValue(data[1][i][day]);
                }
                if (data[2][i][day] != null) {
                    cell = row.getCell(5 + (day * 6));
                    cell.setCellValue(data[2][i][day]);
                }
            }
        }
 
//edit 2
        for (int rowIndex = 2; rowIndex < 4; rowIndex++) {
            row = mySheet.getRow(rowIndex);
            for (int cellDay = 0; cellDay < 5; cellDay++) {
                if (data[rowIndex + 1][0][cellDay] != null) {
                    cell = row.getCell(1 + (cellDay * 6));
                    cell.setCellValue(data[rowIndex + 1][0][cellDay]);
                }
            }
        }
        myInput.close();
 
        File file2 = new File(context.getExternalFilesDir(null), "Arkusz pracy.xls");
        FileOutputStream os = null;
 
        try {
            os = new FileOutputStream(file2);
            myWorkBook.write(os);
            Log.w("FileUtils", "Writing file" + file);
            Toast.makeText(context, "File ready ", Toast.LENGTH_SHORT).show();
            os.close();
        } 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) {
            }
        }
 
    } catch (Exception e) {
        e.printStackTrace();
 
    }
}

sorki za wcześniejszy post

0

Uwagi:

  • za długa metoda
  • magiczne cyfry - nie wiadomo, dlaczego jest 5,7 albo 6
  • niepotrzebny static na metodzie
  • niepotrzebne przedrostki "my"
  • niepotrzebne komentarze
  • zamiast robić null-checki, można użyć Optionala (w Androidzie mamy Javę 7, więc możesz wziąć Optionala z Guavy)
  • jak chcesz do odpalać w Androidzie, to powinieneś pomyśleć o asynchroniczności - jeśli będziesz miał duży plik do przetworzenia albo słabszy telefon, aplikacja zamrozi UI (zawiesi się) na dłuższą chwilę albo całkowicie przestanie odpowiadać - należy dokonać przetwarzania w tle i zwrócić wynik do UI, gdy wszystko będzie gotowe
0

Z góry dzięki za odpowiedź.
Jeśli chodzi o asynchroniczność to odrzuciłem to bo w tym przypadku jest zbędna, ta jedna metoda wczytuje gotowy plik- niezmienny mały arkusz.
Odnośnie liczb... wydają się bez sensu ale są takie a nie inne gdyż określają konkretne komórki (grupy komórek).
statika wywaliłem chwile po wrzuceniu kodu :)
Możesz powiedzieć coś więcej o tych null-checkach? bo w sumie pierwsze słyszę książka i kursy nie wspominały o czymś takim.

tak lepiej ?

private void insertData(HSSFWorkbook workbook, String data[][][]) {
        HSSFSheet sheet=workbook.getSheetAt(0);
        HSSFRow row;
        Cell cell;

        for (int i=0; i<7;i++) {
            row = sheet.getRow(i+5);
            for (int day = 0; day < 7; day++) {
                if (data[0][i][day]!=null) {
                    cell = row.getCell(0 + (day * 6));
                    cell.setCellValue(data[0][i][day]);
                }
                if (data[1][i][day]!=null) {
                    cell = row.getCell(4 + (day * 6));
                    cell.setCellValue(data[1][i][day]);
                }
                if (data[2][i][day]!=null) {
                    cell = row.getCell(5 + (day * 6));
                    cell.setCellValue(data[2][i][day]);
                }
            }
            for(int rowIndex=2; rowIndex<4;rowIndex++) {
                row=sheet.getRow(rowIndex);
                for (int cellDay=0;cellDay<5;cellDay++) {
                    if (data[rowIndex+1][0][cellDay]!=null) {
                        cell = row.getCell(1 + (cellDay * 6));
                        cell.setCellValue(data[rowIndex + 1][0][cellDay]);
                    }
                }
            }
        }

    }
    private void editExcel(Context context, String filename, String data[][][]) {
        try {
            InputStream input=getAssets().open(filename);
            HSSFWorkbook workbook=new HSSFWorkbook(input);
            insertData(workbook, data);
            input.close();
            try {
                FileOutputStream outputStream=new FileOutputStream(new File(context.getExternalFilesDir(null), "Arkusz pracy.xls"));
                workbook.write(outputStream);
                Log.w("FileUtils", "Writing file" + filename);
                Toast.makeText(context, "Arkusz pracy utworzony: " , Toast.LENGTH_SHORT).show();
                outputStream.close();

            } catch (IOException e) {
                Toast.makeText(context, "Błąd zapisu" , Toast.LENGTH_SHORT).show();
                Log.w("FileUtils", "Error writing " + filename, e);
            }

        } catch (IOException e) {
                Toast.makeText(context, "Błąd odczytu arkusza", Toast.LENGTH_LONG).show();
            Log.w("FileUtils", "Error reading" + filename, e);
        }

    }

Idąc za radami zdobywając nową wiedze teraz aktualnie taki efekt.
Mam nadzieję iż jest lepiej. Myślę iż trochę na pewno.

MainActivity.java

private void saveEditedExcel(Context context, String data[][][])
    {
        if (!isExternalStorageAvailable() || isExternalStorageReadOnly())
        {
            showToast(R.string.storage_not_vailable);
            Log.e(TAG, "Storage not available or read only");
            return;
        }
        try
        {
            InputStream input=getAssets().open("myExcel.xls");
            HSSFWorkbook workbook=new HSSFWorkbook(input);
            ExcelFunctions.insertDataToExcel(workbook, data);
            input.close();
            try
            {

                FileOutputStream outputStream=new FileOutputStream(new File(context.getExternalFilesDir(null), "Arkusz pracy.xls"));
                workbook.write(outputStream);
                Log.w("FileUtils", "Writing file myExcel.xls");
                showToast(R.string.writing_file);
                outputStream.close();

            }
            catch (IOException e)
            {
                showToast(R.string.writing_error);
                Log.w("FileUtils", "Error writing myExcel.xls", e);
            }
        }
        catch (IOException e)
        {
            showToast(R.string.reading_file_error);
            Log.w("FileUtils", "Error reading myExcel.xls", e);
        }
    }


    private void readExcelFile(Context context, String data[][][])
    {
        if (!isExternalStorageAvailable() || isExternalStorageReadOnly())
        {
            showToast(R.string.storage_not_vailable);
            Log.e(TAG, "Storage not available or read only");
            return;
        }
        try
        {
            File file=new File(context.getExternalFilesDir(null), "Arkusz pracy.xls");
            InputStream input=new FileInputStream(file);
            HSSFWorkbook workbook=new HSSFWorkbook(input);
            ExcelFunctions.readDataFromExcel(workbook, data);
            input.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            showToast(R.string.reading_file_error);
        }
    }

 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 void showToast(Object text)
    {
        Toast.makeText(getBaseContext(),text.toString(),Toast.LENGTH_LONG).show();
    }

ExcelFunctions.java - odpowiada głównie za operacje na konkretnych(niezmiennie) komórkach, stąd takie zmienne w pętlach.

public class ExcelFunctions extends MainActivity {

    public static void insertDataToExcel(HSSFWorkbook workbook, String data[][][])
    {
        HSSFRow row;
        Cell cell;

        HSSFSheet sheet=workbook.getSheetAt(0);
        for (int i=0; i<7;i++)
        {
            row = sheet.getRow(i+5);
            for (int day = 0; day < 7; day++)
            {
                if (data[0][i][day]!=null)
                {
                    cell = row.getCell(0 + (day * 6));
                    cell.setCellValue(data[0][i][day]);
                }
                if (data[1][i][day]!=null)
                {
                    cell = row.getCell(4 + (day * 6));
                    cell.setCellValue(data[1][i][day]);
                }
                if (data[2][i][day]!=null)
                {
                    cell = row.getCell(5 + (day * 6));
                    cell.setCellValue(data[2][i][day]);
                }
            }
            for(int rowIndex=2; rowIndex<4;rowIndex++)
            {
                row=sheet.getRow(rowIndex);
                for (int cellDay=0;cellDay<5;cellDay++)
                {
                    if (data[rowIndex+1][0][cellDay]!=null)
                    {
                        cell = row.getCell(1 + (cellDay * 6));
                        cell.setCellValue(data[rowIndex + 1][0][cellDay]);
                    }
                }
            }
        }
    }
    public static  void readDataFromExcel (HSSFWorkbook workbook, String data[][][])
    {
        Cell cell;
        HSSFRow row;
        HSSFSheet sheet=workbook.getSheetAt(0);
        for (int i=0; i<7;i++) {
            row = sheet.getRow(i+5);
            for (int day = 0; day < 7; day++)
            {
                cell = row.getCell(0 + (day * 6));
                data[0][i][day]=cell.toString();
                cell = row.getCell(4 + (day * 6));
                data[1][i][day]=cell.toString();
                cell = row.getCell(5 + (day * 6));
                data[2][i][day]=cell.toString();
            }
        }
        for(int rowIndex=2; rowIndex<4;rowIndex++)
        {
            row=sheet.getRow(rowIndex);
            for (int cellDay=0;cellDay<5;cellDay++)
            {
                cell = row.getCell(1 + (cellDay * 6));
                data[rowIndex + 1][0][cellDay]=cell.toString();
            }
        }
    }
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1