使用Jxcell和POI给Excel文件添加打开密码

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();
	}






下载jxcell.jar


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值