如何使用 Java 对 Excel 文档进行数字签名

这篇简洁的文章包含有关如何使用 Java 对 Excel 文档进行数字签名的所有信息。它包含以编程方式执行此任务所需的逻辑步骤以及可运行的示例代码,以使用 Java 在 Excel 中插入电子签名。您还将学习自定义此过程以使用 PFX 创建数字签名,然后将此签名放入 Excel 文件,然后将其保存为 XLSX 文件或任何其他支持的格式。

使用 Java 在 Excel 中创建数字签名的步骤

  1. 配置环境以使用存储库中的 Aspose.Cells 对 Excel 文件进行签名
  2. 实例化一个 Keystore 并使用证书文件名和密码加载证书
  3. 使用上述密钥库和私钥密码创建一个 digital signature
  4. 为数字签名提供注释、签名日期和时间
  5. 创建数字签名集合并将新创建的数字签名添加到其中
  6. 加载 workbook 并将数字签名集合添加到其中
  7. 保存数字签名的工作簿

这些步骤描述了如何使用 Java 在 Excel 中创建电子签名的过程。介绍了一个逐步的过程,首先使用 PFX 证书和私钥密码创建一个密钥库,然后创建一个数字签名集合,并将在密钥库的帮助下创建的新数字签名添加到该集合中。在最后一步中,加载目标工作簿并将数字签名集合添加到其中。

使用 Java 在 Excel 中放置数字签名的代码

import java.io.FileInputStream;
import java.io.InputStream;
import com.aspose.cells.DigitalSignature;
import com.aspose.cells.DigitalSignatureCollection;
import com.aspose.cells.Workbook;
public class AsposeTest {
public static void main(String[] args) throws Exception {//Main function to add a digital signature to a spreadsheet in java
// Instantiate a license
com.aspose.cells.License slidesLicense = new com.aspose.cells.License();
slidesLicense.setLicense("Aspose.Total.lic");
// Using the cryptography PKCS12, create a Keystore
java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12");
// Load certificate into the InputStream
InputStream inStreamCert = new FileInputStream("TestCert1.pfx");
// Load the certificate into the Keystore by providing the certificate file and its password
keyStore.load(inStreamCert, "testcert1".toCharArray());
// Create the digital signature
DigitalSignature digtSign = new DigitalSignature(keyStore, "testcert1", "New digital signature is added to a workbook",com.aspose.cells.DateTime.getNow());
// Instantiate a collection of digital signatures
DigitalSignatureCollection digtSignColl = new DigitalSignatureCollection();
// Add the digital signature to the collection
digtSignColl.add(digtSign);
// Load the spreadsheet
Workbook wbToBeSigned = new Workbook("sampleSpreadsheet.xlsx");
// Add the collection of digital signatures to the workbook
wbToBeSigned.addDigitalSignature(digtSignColl);
// Save the workbook with an electronic signature
wbToBeSigned.save("outputDigitallySignedByCells.xlsx");
System.out.println("Done");
}
}

在此使用 Java 对 Excel 进行数字签名的代码中,使用加密 PKCS12 创建密钥库,然后将证书文件加载到其中。 DigitalSignature 是通过提供密钥库、私钥密码、注释和用户提供的签名时间来创建的,但是您也可以添加签名图像、提供者 ID 和 XAdESType。输出工作簿可以保存为任何支持的格式,如 XLSX、XLS、XLSM、ODS、XLSB 等。

本教程分享了对 Excel 文件进行数字签名的过程,但是如果您想了解将 Excel 转换为图像的过程,请参阅 如何在 Java 中将 Excel 工作表转换为图像 上的文章。

 简体中文