Skip to content

Instantly share code, notes, and snippets.

import com.aspose.cloud.cells.client.ApiException;
import com.aspose.cloud.cells.model.FileInfo;
import com.aspose.cloud.cells.model.FilesResult;
import com.aspose.cloud.cells.model.ProtectWorkbookRequest;
import com.aspose.cloud.cells.request.PostProtectRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
public class Example_PasswordProtectWorkbook {
public void Run() throws IOException, ApiException {
try {
String clientID = "ID";
String clientSecret = "Secret";
String apiBaseUrl = "https://api.aspose.cloud";
String apiVersion = "v3.0";
// Source and output file names
String localPath = "C:/ExcelFiles/";
String inputFileName = "Source.xlsx";
CellsApi protectXlsxtFileApi = new CellsApi(clientID, clientSecret, apiVersion, apiBaseUrl);
HashMap<String, File> mapFiles = new HashMap<>();
mapFiles.put(inputFileName, new File(localPath + inputFileName));
ProtectWorkbookRequest protectXlsxRequest = new ProtectWorkbookRequest();
protectXlsxRequest.setEncryptWithPassword("test");
protectXlsxRequest.setAwaysOpenReadOnly(true);
PostProtectRequest postProtectRequest = new PostProtectRequest();
postProtectRequest.setFile(mapFiles);
postProtectRequest.setProtectWorkbookRequest(protectXlsxRequest);
FilesResult fileResult = protectXlsxtFileApi.postProtect(postProtectRequest);
for (FileInfo file : fileResult.getFiles()) {
try {
File destinationFile = new File(localPath + "protected_" + file.getFilename());
// Create necessary parent directories
destinationFile.getParentFile().mkdirs();
try (FileInputStream inputStream = new FileInputStream(file.getFileContent());
FileOutputStream outputStream = new FileOutputStream(destinationFile)) {
byte[] buffer = new byte[4096]; // Buffer size of 4KB
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("XLSX file writing completed");
} catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception ex) {
System.out.println("An error occurred:" + ex.getMessage());
}
}
}
catch (Exception ex) {
System.out.println("An error occurred:" + ex.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment