准备包:
poi-security-0.0.1.jar是自己写的,下载地址:http://download.youkuaiyun.com/detail/zou_hailin226/9137123
其它的包大家应该知道,就不重复说了,但是有几个注意的地方。第一:poi包必需地3.10-FINAL以后版本;第二:我写的例子是excel2007和以后版本的
废话不多说,直接上代码,代码中“12345”是指的加密和解密的密码
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import br.com.starcode.poisecurity.DocumentType;
import br.com.starcode.poisecurity.decryptor.WorksheetDecryptor;
import br.com.starcode.poisecurity.encryptor.WorksheetEncryptor;
/**Excel加密
* @author zouhailin
* 2015-9-24
*/
public class ExcelSecurity {
/**excel加密
* @throws Throwable
*/
@Test
public void encryptExcel(){
try {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("test1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("test1");
ByteArrayOutputStream os = new ByteArrayOutputStream();
wb.write(os);
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
os.reset();
WorksheetEncryptor.encrypt(is, os, DocumentType.XML, "12345");
is.close();
os.flush();
os.close();
bytesWriteLocal("d://test//test.xlsx", os.toByteArray());
System.out.println("End");
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Excel解密
*/
@Test
public void decryptExcel(){
try {
FileInputStream is = new FileInputStream(new File("d://test//test.xlsx"));
Workbook wb = (XSSFWorkbook) WorksheetDecryptor.decrypt(
is,
DocumentType.XML,
"12345");
Sheet sheet = wb.getSheet("test1");
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
System.out.println(cell.getStringCellValue());
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("End");
}
public static void bytesWriteLocal(String path,byte[] b){
File file = new File(path);
FileOutputStream out = null;
ByteArrayInputStream bIn = null;
try {
if (!file.exists()) {
file.createNewFile();
}
out = new FileOutputStream(file);
bIn = new ByteArrayInputStream(b);
int i = 0;
while((i = bIn.read())!=-1){
out.write(i);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}finally {
if(bIn!=null) {
try {
bIn.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if(out!=null) {
try {
out.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
}