I have successfully Encrypted an existing Excel file (.xlsx format) but i have no idea how to Encryt Excel file of .xls format , so far i have zipped and then encrypted the .xls but i want the Excel file(.xls) to be encrypted.
i have used POI for these operations.
if(!CSVToEXCEL.pw.equals("NA")){
if(CSVToEXCEL.oformat.equals("xlsx")){
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(fs, EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword(CSVToEXCEL.pw);
OPCPackage opc = OPCPackage.open(new File(CSVToEXCEL.opath), PackageAccess.READ_WRITE);
OutputStream os = enc.getDataStream(fs);
opc.save(os);
opc.close();
FileOutputStream fos = new FileOutputStream(CSVToEXCEL.opath);
fs.writeFilesystem(fos);
System.out.println("File created..."+CSVToEXCEL.opath);
fos.close();
}
else {
// if file is of '.xls' format
System.out.println("xls cannot be Encrypted...");
ZipAndProtectReport zipAndProtectReport = new ZipAndProtectReport();
String xlsoutputzip = zipAndProtectReport.ZipAndProtectMethod(CSVToEXCEL.opath,CSVToEXCEL.pw);
System.out.println("Zip Created..... path: "+xlsoutputzip);
}
}
else
System.out.println("File Created....."+CSVToEXCEL.opath);
}
CSVToEXCEL is class name , CSVToEXCEL.opath is the output path location, CSVToEXCEL.pw is password ZipAndProtectReport is another class for zipping and then password protecting.
i want to know how can i make .xls to be password protected without zipping it.
Try this link http://www.quicklyjava.com/create-password-protected-excel-using-apache-poi/.
Since you already are using POI, it would be easier to use this.
Maybe you can create a xlsx file,and put the xls file's data into xlsx file,and encryt xlsx file?
Related
I am trying to create the csv file with data as follows
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
String fileLocation = null;
try {
// Set the header columns name for worksheet
createHeader(workbook, sheet);
// populate the data
createWorkbookRows(ker, sheet, kerList, AerList);
String tempDir = System.getProperty("java.io.tmpdir");
File file = new File(tempDir);
fileLocation = file.getAbsolutePath() + FileSystems.getDefault().getSeparator() + "MyData.csv";
FileOutputStream outputStream = new FileOutputStream(fileLocation);
workbook.write(outputStream);
}catch(Exception e){
}
With the above code I am able to generate the csv file, but when I try to open the file the below error it is showing
When I click on yes it is showing the data properly in excel file.
I have verified the csv file by opening in Notepad++ also it is showing in non understandable language instead of comma seperated.
Please suggest how can I solve the above issue.
POI writes a binary Excel file. Your extension "csv" is wrong. It should be "xlsx" because you use XSSFWorkbook.
I need to open an existing *.xlsx Excel file, make some modifications, and then save it as a new file (or stream it to the frontend without saving). The original file must remain unchanged.
For Memory reasons, I avoid using FileInputStream (as described here: http://poi.apache.org/spreadsheet/quick-guide.html#FileInputStream )
// XSSFWorkbook, File
OPCPackage pkg = OPCPackage.open(new File("file.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
....
pkg.close();
JFileChooser fileOpen = new JFileChooser();
fileOpen.showOpenDialog(theFrame); // gives you an open file dialog
readFile(fileOpen.getSelectedFile()); // write you reading content in reaFile method
JFileChooser fileSave = new JFileChooser();
fileSave.showSaveDialog(Frame); //gives you a dialog box for saving
saveFile(fileSave.getSelectedFile()); // write your saving content in saveFile method
Here is how this can be done when using OPCPackage to read (try/catch/finally ommitted for readibility):
OPCPackage pkg = OPCPackage.open("existingFile.xlsx");
XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(pkg);
make your modifications... XSSFSheet sheet = wb.getSheetAt(0); ...
fos = new FileOutputStream("outputFileName.xlsx");
wb.write(fos);
pkg.close();
fos.close();
Faces.sendFile(new File(outputFileName)
In order for this to work, it is important to use different file path for Input and for Output.
The last line sends the File to your Browser using Omnifaces.
See this question for more Information:
enter link description here
Here is my final solution, which I ended up using. This has the advantage, that no Files are saved anywhere. I also added the following line:
XSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);
which will ensure that all formulas are updated.
Again, I ommitted all the try/catch/finally.
OPCPackage pkg = OPCPackage.open("existingFile.xlsx");
XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(pkg);
// make your modifications...
XSSFSheet sheet = wb.getSheetAt(0);
//
XSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);
ByteArrayOutputStream os = new ByteArrayOutputStream();
wb.write(os);
pkg.close();
os.close();
Faces.sendFile(os.toByteArray(), "file.xlsx", true);
In order for this to work, it is important to use different file path for Input and for Output.
The last line sends the File to your Browser using Omnifaces.
I need to unprotect a protected xlsx file.e.g Book1.xlsx
Below code runs fine for the first time, Reads Book1.xlsx, decrypt it and again write it to the same filename.
public static void unprotectXLSXSheet(String fileName, String password) {
try{
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(fileName));
EncryptionInfo info = new EncryptionInfo(fs);
Decryptor d = Decryptor.getInstance(info);
d.verifyPassword(password);
InputStream is = d.getDataStream(fs);
System.out.println(is.available());
XSSFWorkbook wb = new XSSFWorkbook(OPCPackage.open(is));
FileOutputStream fileOut;
fileOut = new FileOutputStream(fileName);
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}catch(FileNotFoundException ex){
ex.printStackTrace();
}catch(IOException ex){
ex.printStackTrace();
But when the same code tries to access the newly created unprotected Book1.xlsx(or anyother unprotected xlsx file) it fails and showing
Exception in thread "main" org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:131)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:104)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:138)
at com.wolseley.Excel.TestMainDummy.unprotectXLSXSheet(TestMainDummy.java:113)
at com.wolseley.Excel.TestMainDummy.main(TestMainDummy.java:52)
i need help in reading xlsx file and also unlock it using password, as done above.
Basically the following line of code doesn't work for Office 2007+ XML documents:
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(fileName));
So you'll first need to check the header in the input stream whether it's supported by calling this:
POIFSFileSystem.hasPOIFSHeader(is)
and only decrypting if the above returns true. The hasPOIFSHeader method requires an input stream that supports mark/reset, so check that as well and wrap it in a PushbackInputStream if not.
Putting it all together then becomes something like this:
public static void unprotectXLSXSheet(String fileName, String password) throws Exception {
InputStream is = null;
FileOutputStream fileOut = null;
try {
is = new FileInputStream(fileName);
if (!is.markSupported()) {
is = new PushbackInputStream(is, 8);
}
if (POIFSFileSystem.hasPOIFSHeader(is)) {
POIFSFileSystem fs = new POIFSFileSystem(is);
EncryptionInfo info = new EncryptionInfo(fs);
Decryptor d = Decryptor.getInstance(info);
d.verifyPassword(password);
is = d.getDataStream(fs);
}
System.out.println(is.available());
XSSFWorkbook wb = new XSSFWorkbook(OPCPackage.open(is));
fileOut = new FileOutputStream(fileName);
wb.write(fileOut);
fileOut.flush();
} finally {
if (is != null) {
is.close();
}
if (fileOut != null) {
fileOut.close();
}
}
}
Below old Stack Overflow answer may be help you out from this.
Reading property sets from Office 2007+ documents with java poi
The class you'll want is POIXMLProperties, something like:
OPCPackage pkg = OPCPackage.open(new File("file.xlsx"));
POIXMLProperties props = new POIXMLProperties(pkg);
System.out.println("The title is " + props.getCorePart().getTitle());
From POIXMLProperties you can get access to all the built-in properties, and the custom ones too!
I have an xlsm Excel file with macros in it already.The file is 2M big ( I guess from the many macros in there).
I just want to write to 1 cell in the file and I am using POI interface. Here is the code
Workbook wb;
wb = new XSSFWorkbook(
OPCPackage.open("test.xlsm")
);
Sheet sheet = wb.getSheet("Sheet1");
Cell c = sheet.getRow(1).getCell(8);
System.out.print("Sheet Name " + sheet.getSheetName());
System.out.print("Cell is " + c.getNumericCellValue());
c.setCellValue(4);
FileOutputStream fileOut=new FileOutputStream("test.xlsm");
wb.write(fileOut);
fileOut.close();
System.out.println("done1");
It reads the value correctly and then it seems to be stuck at wb.write(fileout), never finishes. What am I doing wrong? Is there a way to modfy an excel sheet that has macros in it?
Thank you
To modify existing file, use InputStream and OutputStream.
File file = new File("test.xlsm");
FileInputStream inputStream = new FileInputStream(file);
OPCPackage.open(inputStream);
......
FileOutputStream fileOut=new FileOutputStream("test.xlsm");
wb.write(fileOut);
fileOut.close();
For more sure, before to write the file close the InputStream.
I am trying to generate Excel reports using Apache POI 3.6 (latest).
Since POI has limited support for header and footer generation (text only), I decided to start from a blank excel file with the header already prepared and fill the Excel cells using POI (cf. question 714172).
Unfortunately, when opening the workbook with POI and writing it immediately to disk (without any cell manpulation), the header seems to be lost.
Here is the code I used to test this behavior:
public final class ExcelWorkbookCreator {
public static void main(String[] args) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(new File("dump.xls"));
InputStream inputStream = ExcelWorkbookCreator.class.getResourceAsStream("report_template.xls");
HSSFWorkbook workbook = new HSSFWorkbook(inputStream, true);
workbook.write(outputStream);
} catch (Exception exception) {
throw new RuntimeException(exception);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException exception) {
// Nothing much to do
}
}
}
}
}
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = new HSSFSheet();
Header header = sheet.getHeader() //get header from workbook's sheet
header.setCenter(HSSFHeader.font("COURIER", "Normal")+ HSSFHeader.fontSize((short) 15) + "Hello world" +new Date()); // set header with desire font style
FileOutputStream fileOut = new FileOutputStream("C:\\book.xls");
workbook.write(fileOut);
The headers of the Excel file are preserved as long as those headers are supported in Excel 97-2003. For example, images are supported (I just tried it), but colored text is not.
The tricky part of this is that your Excel template file "dump.xls" must be in Excel 97-2003 format. Please note: this is not the file extension, but the actual contents of the file. The newest Excel will happily save the newest formatting in a .xls file, which POI cannot read.
To test this, save your Excel file as an .xls file. Important - If you receive a compatibility warning, then you must click the "Correct" link in the dialog to correct the Excel. Just clicking Proceed makes the Excel file invalid to POI.
Once you have a real .xls file (with compatible contents) then your code works. I just tested it myself:
public static void main(String[] args) throws Exception {
try (FileInputStream fis = new FileInputStream("./report_template.xls");
FileOutputStream fos = new FileOutputStream("./dump.xls")) {
HSSFWorkbook wb = new HSSFWorkbook(fis);
wb.write(fos);
}
}