创建受密码保护的 Excel 文件或使用现有模板并使其受密码保护。不过,这将为用户提供“只读”访问权限。下面是一个示例,其中我有一个包含密码“secret”的Excel文件:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
public class ProtectedExcelFile {
public static void main(final String... args) throws Exception {
String fname = "C:\\Documents and Settings\\sadutta\\Desktop\\sample.xls";
FileInputStream fileInput = null;
BufferedInputStream bufferInput = null;
POIFSFileSystem poiFileSystem = null;
FileOutputStream fileOut = null;
try {
fileInput = new FileInputStream(fname);
bufferInput = new BufferedInputStream(fileInput);
poiFileSystem = new POIFSFileSystem(bufferInput);
Biff8EncryptionKey.setCurrentUserPassword("secret");
HSSFWorkbook workbook = new HSSFWorkbook(poiFileSystem, true);
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("THIS WORKS!");
fileOut = new FileOutputStream(fname);
workbook.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(), "");
workbook.write(fileOut);
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
finally {
try {
bufferInput.close();
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
try {
fileOut.close();
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}
同样,您应该能够编写或修改现有的模板。完成后,覆盖模板。如果模板应多次使用,则可能需要将模板复制到其他某个位置,然后使用代码对其进行修改。