The fomat and extension of "file.csv" doesn't match - java

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.

Related

Cannot read Excel file with Arabic content using Java

I try to read an Excel file with Arabic content. I made it to read the file but the problem is that the result contains many question marks instead of the correct content.
How I can read the content correctly?
File src = new File("C:\\ExcelRW\\CarePost.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 = wb.getSheetAt(0);
String post_message = sheet1.getRow(1).getCell(4).getStringCellValue();
System.out.print(post_message);
This result: ???? ????? ????
Use the following Code
sheet1.getRow(1).getCell(4).getRichStringCellValue();
instead of:
sheet1.getRow(1).getCell(4).getStringCellValue()
This applies to UTF-8 encoded characters like Chinese, Arabic or Japanese.

xlsx file created with apache poi cannot be opened

I am using Apache POI 3.17 to create xlsx files and filling it with data from the db. The file gets created fine but when I try to open it, I get 'incompatible format' error even though when I inspect the file, I can see that it is a Microsoft spreadsheet file. I looked at here,here and here and tried all these examples but didn't help and I don't know where the problem is. Here is my file creation code:
File excelFile = new File("C:\\myFile.xlsx"); //a new file to be created
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(rowIndex);
Cell cell;
//some font and style creation
for(String eachHeader : headers) {
cell = row.createCell(cellIndex);
cell.setCellValue(eachHeader);
cell.setCellStyle(headerStyle);
cellIndex++;
}
//some more row and cell creation
try {
//finally try to write all this content into the excel file
OutputStream out = new FileOutputStream(excelFile);
workbook.write(out);
out.close();
logger.debug("Worksheet created: " + excelFile.getAbsolutePath());
}catch(Exception exc) {
logger.error("Error occured while creating or writing to the excel file: " + exc.getMessage());
}
Again, the file is created fine with some data in it as I can see that the size is not 0, but just cannot open it, why??

How can I open an existing *.xlsx file, make modifications, then save as new file (leaving original file untouched?)

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.

Way to Encrypt(Password protect) .xls file which is already created

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?

append data into xlsx file through java

I am using Apache POI for writing into .xlsx file. I can write into .xlsx file but I am unable to append new content. How can I append new content in the .xlsx file?
My Code is:
public static void write(){
try {
Workbook[] wbs = new Workbook[]{new XSSFWorkbook()};
Workbook workbook=wbs[0];
org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet();
System.out.println(sheet.getSheetName());
Row row = sheet.createRow(2);
for(int i=0;i<10;i++){
Cell cell=row.createCell(i);
cell.setCellValue("Sun System");
}
FileOutputStream fout=new FileOutputStream("D:/Test.Xlsx");
workbook.write(fout);
fout.close();
} catch (Exception e) {
}
}
The first thing U've to do :
When you're working with Excel 2007 format, its more wise to use XSSF-Implementations, because you've used abstract implementations. Always remember this when using any implementation.
To append to an existing file you need to reach the end of the rows in that particular workbook sheet. This can be achieved by:
int rows = sheet.getPhysicalNumberOfRows(); // or sheet.getLastRowNum();
After that you can create new cells with the XSSF- Implementation classes. For more information refer to this page
You should open the existing file instead of creating a new one if you want to append, see also this stackoverflow question:
Edit existing excel files using jxl api / Apache POI
You are creating a new workbook each time this is run youd want to create a FileInputStream with a file path to the excel file and then use that input stream to get the XSSF workbook you want to edit
FileInputStream fis = new FileInputStream(filePath);
XSSFWorkbook workBook = new XSSFWorkbook(fis);
then in order to get a specific sheet you simply just use the .getSheet or getSheetAt methods that are apart of workBook. then create and set cells

Categories

Resources