在 Excel 工作簿中隐藏敏感数据是企业内部或与合作伙伴共享报告时的常见需求。 GroupDocs.Merger Cloud SDK for Java 使开发人员能够通过简单的 REST API 为 XLSX 文件添加密码保护。 在本指南中,您将学习如何实现 通过 REST 在 Java 中对 Excel 进行密码保护,查看完整的 Java 示例,并运行等效的 cURL 命令以进行云集成。

前置条件和设置

在开始之前,请确保您具备以下内容:

  • 已安装 Java 8 或更高版本。
  • 用于依赖管理的 Maven 或 Gradle。
  • 拥有 client IDclient secret 的 GroupDocs Cloud 账户。
  • 访问存放 Excel 文件的云存储。

将 Maven 依赖添加到您的 pom.xml(或等效的 Gradle 代码片段):

<dependency>
    <groupId>com.groupdocs</groupId>
    <artifactId>groupdocs-merger-cloud</artifactId>
    <version>25.11</version>
</dependency>

您可以从下载页面下载最新的 JAR 包。添加依赖后,使用您的凭据创建一个配置对象:

String clientId = "YOUR_CLIENT_ID";
String clientSecret = "YOUR_CLIENT_SECRET";

Configuration config = new Configuration(clientId, clientSecret);
MergerApi mergerApi = new MergerApi(config);

客户端准备就绪后,您可以继续实际的密码保护工作流。

通过 REST 在 Java 中对 Excel 进行密码保护:逐步演练

第一步:加载源文档

在您的云存储中定义源 XLSX 文件的位置。

FileInfo inputFile = new FileInfo();
inputFile.setFilePath("input.xlsx");   // source Excel file

第 2 步:设置目标路径

指定受保护工作簿的保存位置。

String outputPath = "output_protected.xlsx"; // destination file

第3步:配置密码保护选项

创建一个 ProtectOptions 对象,附加文件信息、输出路径以及所需的密码。

ProtectOptions protectOptions = new ProtectOptions();
protectOptions.setFileInfo(inputFile);
protectOptions.setOutputPath(outputPath);
protectOptions.setPassword("MySecretPassword"); // desired password

步骤 4:构建保护文档请求

将选项包装在 ProtectDocumentRequest 中。

ProtectDocumentRequest request = new ProtectDocumentRequest(protectOptions);

第5步:执行请求并处理响应

调用 API 方法并处理任何错误。

try {
    mergerApi.protectDocument(request);
    System.out.println("Excel file has been password protected successfully.");
    System.out.println("Protected file stored at: " + outputPath);
} catch (ApiException e) {
    System.err.println("Error while protecting the Excel file:");
    System.err.println("Status Code: " + e.getCode());
    System.err.println("Message: " + e.getMessage());
}

有关每个类的更多详细信息,请参阅 API 参考

完整的通过 REST 在 Java 中对 Excel 进行密码保护的示例

以下代码演示了从头到尾的完整过程。

import com.groupdocs.merger.cloud.ApiException;
import com.groupdocs.merger.cloud.Configuration;
import com.groupdocs.merger.cloud.api.MergerApi;
import com.groupdocs.merger.cloud.model.FileInfo;
import com.groupdocs.merger.cloud.model.ProtectOptions;
import com.groupdocs.merger.cloud.model.requests.ProtectDocumentRequest;

public class ProtectExcelExample {
    public static void main(String[] args) {
        // Replace with your actual client credentials
        String clientId = "YOUR_CLIENT_ID";
        String clientSecret = "YOUR_CLIENT_SECRET";

// Initialize the API configuration
        Configuration config = new Configuration(clientId, clientSecret);
        MergerApi mergerApi = new MergerApi(config);

// Define input and output file locations (relative to the storage root)
        FileInfo inputFile = new FileInfo();
        inputFile.setFilePath("input.xlsx");          // source Excel file
        String outputPath = "output_protected.xlsx";  // destination file

// Set password protection options
        ProtectOptions protectOptions = new ProtectOptions();
        protectOptions.setFileInfo(inputFile);
        protectOptions.setOutputPath(outputPath);
        protectOptions.setPassword("MySecretPassword"); // desired password

// Build the request
        ProtectDocumentRequest request = new ProtectDocumentRequest(protectOptions);

try {
            // Execute the password protection operation
            mergerApi.protectDocument(request);
            System.out.println("Excel file has been password protected successfully.");
            System.out.println("Protected file stored at: " + outputPath);
        } catch (ApiException e) {
            System.err.println("Error while protecting the Excel file:");
            System.err.println("Status Code: " + e.getCode());
            System.err.println("Message: " + e.getMessage());
        }
    }
}

注意: 此代码示例演示了核心功能。在将其用于项目之前,请确保更新文件路径(input.xlsxoutput_protected.xlsx)以匹配实际文件位置,确认已正确安装所有必需的依赖项,并在开发环境中进行彻底测试。如果遇到任何问题,请参阅官方文档或联系支持团队获取帮助。

使用 cURL 通过 REST API 保护 Excel 工作簿

下面是一组 cURL 命令,它们直接针对 REST 端点执行相同的密码保护操作。

1. 进行身份验证并获取访问令牌

curl -X POST "https://api.groupdocs.cloud/v2.0/auth/token" \
     -H "Content-Type: application/json" \
     -d '{
           "client_id": "YOUR_CLIENT_ID",
           "client_secret": "YOUR_CLIENT_SECRET"
         }'

响应中包含一个 access_token,您将在后续调用中使用它。

2. 上传源 XLSX 文件

curl -X PUT "https://api.groupdocs.cloud/v2.0/storage/file/input.xlsx" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/octet-stream" \
     --data-binary @input.xlsx

3. 请求密码保护

curl -X POST "https://api.groupdocs.cloud/v2.0/merger/protect" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
           "fileInfo": { "filePath": "input.xlsx" },
           "outputPath": "output_protected.xlsx",
           "password": "MySecretPassword"
         }'

4. 下载受保护的工作簿

curl -X GET "https://api.groupdocs.cloud/v2.0/storage/file/output_protected.xlsx" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -o output_protected.xlsx

这些命令可让您将保护工作流集成到脚本或 CI 管道中。有关更多详细信息,请参阅官方 API 文档

结论

使用 GroupDocs.Merger Cloud SDK for Java 实现 通过 REST 在 Java 中对 Excel 进行密码保护 非常简单。按照上述步骤,您可以保护 Excel 工作簿的安全,在服务器端应用程序中自动化此过程,并确保敏感数据安全。请记得获取适用于生产环境的正式许可证;产品页面上提供了定价信息,您也可以通过 临时许可证 开始评估该库。祝编码愉快!

常见问题

  • 通过 REST 在 Java 中对 Excel 进行密码保护与本地加密有何不同?
    云 API 在服务器上执行加密,因此您无需在本地管理加密库。SDK 负责请求构建和响应解析,简化了集成。

  • 是否可以设置额外的保护选项,例如只读模式?
    当前的 ProtectOptions 类专注于密码保护。欲获取更高级的安全功能,请查阅 API 参考 以了解任何新参数。

  • 支持哪些文件格式的密码保护?
    Merger API 当前支持 XLSX、DOCXPPTX、以及 PDF 进行加密。请参阅官方文档获取完整列表。

  • 我是否需要许可证才能在开发环境中运行示例?
    开发和测试可以使用临时许可证。生产部署需要付费许可证,您可以通过产品页面购买。

阅读更多