import java.io.IOException;
import com.jxcell.CellException;
import com.jxcell.View;
/**
* 写Excel文件并设置打开密码
*
*/
public class EncryptDecrypt {
public EncryptDecrypt() {
encrypt();
decrypt();
}
/**
* 写Excel文件并设置打开密码
*/
public void encrypt() {
View m_view = new View();
try {
m_view.setTextAsValue(1, 2, "苹果");
m_view.setTextAsValue(1, 3, "香蕉");
m_view.setTextAsValue(1, 4, "桃子");
m_view.setTextAsValue(1, 5, "李子");
m_view.setTextAsValue(2, 1, "商家1");
m_view.setTextAsValue(3, 1, "商家2");
m_view.setTextAsValue(4, 1, "商家3");
m_view.setTextAsValue(5, 1, "商家4");
m_view.setTextAsValue(6, 1, "商家5");
m_view.setTextAsValue(7, 1, "合计");
//插入公式
for (int col = 2; col <= 5; col++)
for (int row = 2; row <= 7; row++)
m_view.setFormula(row, col, "RAND()");
m_view.setFormula(7, 2, "SUM(C3:C7)");
m_view.setSelection("C8:F8");
m_view.editCopyRight();
//写文件并设置密码
m_view.write("E:\\text.xls", "123456");
} catch (CellException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void decrypt() {
View m_view = new View();
try {
//尝试用错误的打开密码读文件
m_view.read("E:\\text.xls", "456789");
m_view.write("E:\\text.xls");
} catch (Exception e) {
//会打印出:Invalid password.表示密码无效。
System.out.println(e.getMessage());
}
}
public static void main(String args[]) {
new EncryptDecrypt();
}
}
请注意,在代码写好几天后我在测试时发现了一个bug,在我的代码中实例化View对象时(new View())线程阻塞,到现在也没找到原因所在,因此请看官慎用。在这种情况下就在网上找到了另外一个办法,用POI对Excel添加打开密码,代码如下。
/**
* 用POI给Excel文件加密
* @param filePath
* @param pwd
* @throws Exception
*/
private static void encryptExcel(String filePath,String pwd) throws Exception{
//POI对Excel文件加密
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword(pwd);
OPCPackage opc = OPCPackage.open(new File(filePath), PackageAccess.READ_WRITE);
OutputStream os = enc.getDataStream(fs);
opc.save(os);
opc.close();
FileOutputStream fos = new FileOutputStream(filePath);
fs.writeFilesystem(fos);
fos.close();
fs.close();
}