Как правильно вставить изображение с помощью библиотеки POI в Android? Когда я вставляю изображение, EXCEL не может прочитать файл. «Excel обнаружил нечитаемый контент в ...» - PullRequest
0 голосов
/ 13 января 2019

Я хотел бы вставить изображение и текст. Когда я вставляю изображение (первый код), EXCEL на ПК не может прочитать файл. EXCEL говорит: «Excel обнаружил нечитаемый контент в ...»

Но, когда я пропускаю код о вставке изображения (просто добавьте текст на EXCEL) EXCEL умеет хорошо читать файл (второй код)

Как я могу исправить свой код?

Я работал на Android Studio 3.2.1 и Galaxy S6

// 1-й код (вставить текст и изображение)

package com.example.yonghwan.d20xlsservicesave1;

import android.content.Intent;
import android.os.Environment;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Toast;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        boolean isPermissionAllowed = isNotiPermissionAllowed();
        if(!isPermissionAllowed) {
            Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            startActivity(intent);
        }

        String storageDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        File dir = new File(storageDir);
        if (!dir.exists()) dir.mkdir();
        String path = storageDir + "/Test5.xlsx";
        File xlsFile = new File(path);


        try {
            storageDir = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/" + Environment.DIRECTORY_DCIM + "/Noti";
            path = storageDir + "/EXTRA.jpg";
            File iconFile = new File(path);
            InputStream inputStream = new FileInputStream(iconFile);
            byte[] bytes = IOUtils.toByteArray(inputStream);

            FileInputStream fileInputStream = new FileInputStream(xlsFile);
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
            XSSFSheet sheet = (XSSFSheet) workbook.getSheet("Sheet1");
            int rowNumber = sheet.getLastRowNum();

            int pictureIndex = workbook.addPicture(bytes, XSSFWorkbook.PICTURE_TYPE_JPEG);
            inputStream.close();

            XSSFCreationHelper helper = workbook.getCreationHelper();
            XSSFDrawing drawing = sheet.createDrawingPatriarch();
            XSSFClientAnchor anchor = helper.createClientAnchor();

            XSSFRow row = sheet.createRow(rowNumber+1);
            XSSFCell cell = row.createCell(1);
            cell.setCellValue("Image test : " + String.valueOf(rowNumber));
            anchor = new XSSFClientAnchor();
            anchor.setCol1(0);
            anchor.setCol2(1);
            anchor.setRow1(rowNumber+1);
            anchor.setRow2(rowNumber+2);

            anchor.setAnchorType(ClientAnchor.MOVE_DONT_RESIZE);

            Picture picture = drawing.createPicture(anchor, pictureIndex);

            OutputStream outputStream = new FileOutputStream(xlsFile);
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            Toast.makeText(getApplicationContext(), "File Saved Successfully", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Failed to save File", Toast.LENGTH_LONG).show();
        }

    }


    private boolean isNotiPermissionAllowed() {
        Set<String> notiListenerSet = NotificationManagerCompat.getEnabledListenerPackages(this);
        String myPackageName = getPackageName();

        for(String packageName : notiListenerSet) {
            if(packageName == null) {
                continue;
            }
            if(packageName.equals(myPackageName)) {
                return true;
            }
        }

        return false;
    }

}

// 2-й код (вставить только текст)

package com.example.yonghwan.d20xlsservicesave1;

import android.content.Intent;
import android.os.Environment;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        boolean isPermissionAllowed = isNotiPermissionAllowed();
        if(!isPermissionAllowed) {
            Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            startActivity(intent);
        }

        String storageDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        File dir = new File(storageDir);
        if (!dir.exists()) dir.mkdir();
        String path = storageDir + "/Test5.xlsx";
        File xlsFile = new File(path);


        try {
            storageDir = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/" + Environment.DIRECTORY_DCIM + "/Noti";
            path = storageDir + "/EXTRA.jpg";
            File iconFile = new File(path);
            InputStream inputStream = new FileInputStream(iconFile);
            byte[] bytes = IOUtils.toByteArray(inputStream);

            FileInputStream fileInputStream = new FileInputStream(xlsFile);
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
            XSSFSheet sheet = (XSSFSheet) workbook.getSheet("Sheet1");
            int rowNumber = sheet.getLastRowNum();

//            int pictureIndex = workbook.addPicture(bytes, XSSFWorkbook.PICTURE_TYPE_JPEG);
//            inputStream.close();

//            XSSFCreationHelper helper = workbook.getCreationHelper();
//            XSSFDrawing drawing = sheet.createDrawingPatriarch();
//            XSSFClientAnchor anchor = helper.createClientAnchor();

            XSSFRow row = sheet.createRow(rowNumber+1);
            XSSFCell cell = row.createCell(1);
            cell.setCellValue("Image test : " + String.valueOf(rowNumber));
//            anchor = new XSSFClientAnchor();
//            anchor.setCol1(0);
//            anchor.setCol2(1);
//            anchor.setRow1(rowNumber+1);
//            anchor.setRow2(rowNumber+2);

//            anchor.setAnchorType(ClientAnchor.MOVE_DONT_RESIZE);

//            Picture picture = drawing.createPicture(anchor, pictureIndex);

            OutputStream outputStream = new FileOutputStream(xlsFile);
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            Toast.makeText(getApplicationContext(), "File Saved Successfully", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Failed to save File", Toast.LENGTH_LONG).show();
        }

    }


    private boolean isNotiPermissionAllowed() {
        Set<String> notiListenerSet = NotificationManagerCompat.getEnabledListenerPackages(this);
        String myPackageName = getPackageName();

        for(String packageName : notiListenerSet) {
            if(packageName == null) {
                continue;
            }
            if(packageName.equals(myPackageName)) {
                return true;
            }
        }

        return false;
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...