如何使用Android应用程序创建和上传谷歌电子表格?

时间:2015-12-03 13:46:48

标签: android spreadsheet google-drive-android-api

我花了太多时间在这上面,所以我想问一下。我想使用android创建和上传谷歌电子表格。我知道我应该使用 Drive API 来执行此操作。我知道如何使用此API(甚至excel文件)创建文件,但当 setMimeType 设置为 application / vnd.google-apps.spreadsheet 时,我在设备上收到错误消息:尝试创建文件时出错。

image/jpeg

2 个答案:

答案 0 :(得分:2)

GDAA目前不支持创建Google文档文件。您必须使用Android应用程序中的Google Drive REST API才能执行此操作。

答案 1 :(得分:2)

@ user3212019,您可以从Android应用上传google驱动器中的excel电子表格,如下所示。

  

我认为您在Google Android网站上了解Quick Start

     

现在使用jxl jar library

创建Excel工作表

现在请关注Start Integrating Google Sign-In并在应用中集成Google SignIn和云端硬盘范围(Drive.SCOPE_FILE)。

现在最后和最后一次复制粘贴到活动中的活动代码下面,然后在saveFileToDrive(file_path)方法中提供Excel工作表路径。

public class UploadFileInGoogleDriveActivity extends Activity {

    private static final String TAG = "tejadroid-quickstart";
    private static final int REQUEST_CODE_SIGN_IN = 0;

    private GoogleSignInClient mGoogleSignInClient;
    private DriveClient mDriveClient;
    private DriveResourceClient mDriveResourceClient;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        signIn();
    }

    /**
     * Start sign in activity.
     */
    private void signIn() {
        Log.i(TAG, "Start sign in");
        mGoogleSignInClient = buildGoogleSignInClient();
        startActivityForResult(mGoogleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);

    }

    /**
     * Build a Google SignIn client.
     */
    private GoogleSignInClient buildGoogleSignInClient() {
        GoogleSignInOptions signInOptions =
                new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestScopes(Drive.SCOPE_FILE)
                        .build();
        return GoogleSignIn.getClient(this, signInOptions);
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SIGN_IN:
                Log.i(TAG, "Sign in request code");
                // Called after user is signed in.
                if (resultCode == RESULT_OK) {
                    Log.i(TAG, "Signed in successfully.");
                    // Use the last signed in account here since it already have a Drive scope.
                    mDriveClient = Drive.getDriveClient(this, GoogleSignIn.getLastSignedInAccount(this));
                    // Build a drive resource client.
                    mDriveResourceClient =
                            Drive.getDriveResourceClient(this, GoogleSignIn.getLastSignedInAccount(this));

                    // Excel Sheet path from SD card
                    final String filePath = "/storage/emulated/0/Expense Manager/ExpenseReport/ExpenseDiary.xls";
                    saveFileToDrive(filePath);
                }
                break;
        }
    }

    /**
     * Create a new file and save it to Drive.
     */
    private void saveFileToDrive(final String filePath) {
        // Start by creating a new contents, and setting a callback.
        Log.i(TAG, "Creating new contents.");

        mDriveResourceClient
                .createContents()
                .continueWithTask(
                        new Continuation<DriveContents, Task<Void>>() {
                            @Override
                            public Task<Void> then(@NonNull Task<DriveContents> task) throws Exception {
                                return createFileIntentSender(task.getResult(), new File(filePath));
                            }
                        })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.w(TAG, "Failed to create new contents.", e);
                            }
                        });
    }

    /**
     * Creates an {@link IntentSender} to start a dialog activity with configured {@link
     * CreateFileActivityOptions} for user to create a new photo in Drive.
     */
    private Task<Void> createFileIntentSender(DriveContents driveContents, File file) throws Exception {
        Log.i(TAG, "New contents created.");

        OutputStream outputStream = driveContents.getOutputStream();
        InputStream in = new FileInputStream(file);
        try {
            try {
                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    outputStream.write(buf, 0, len);
                }
            } finally {
                outputStream.close();
            }
        } finally {
            in.close();
        }


        // Create the initial metadata - MIME type and title.
        // Note that the user will be able to change the title later.
        MetadataChangeSet metadataChangeSet =
                new MetadataChangeSet.Builder()
                        .setMimeType("application/vnd.ms-excel")
                        .setTitle("ExcelSheet.xls")
                        .build();
        // Set up options to configure and display the create file activity.
        CreateFileActivityOptions createFileActivityOptions =
                new CreateFileActivityOptions.Builder()
                        .setInitialMetadata(metadataChangeSet)
                        .setInitialDriveContents(driveContents)
                        .build();

        return mDriveClient
                .newCreateFileActivityIntentSender(createFileActivityOptions)
                .continueWith(
                        new Continuation<IntentSender, Void>() {
                            @Override
                            public Void then(@NonNull Task<IntentSender> task) throws Exception {
                                startIntentSenderForResult(task.getResult(), REQUEST_CODE_CREATOR, null, 0, 0, 0);
                                return null;
                            }
                        });
    }


}

只需调试应用并查看Google云端硬盘,您的文件就存在于驱动器的根文件夹中。