Cannot read Excel file with Arabic content using Java - 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.

Related

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

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.

Read xls file with API POI Exception Initialisation of record 0x203(NumberRecord) left 4 bytes remaining still to be read

I write java class to read xls file, class works fine when I read many xls file, but doesn't work if I try to read a file that I receive, and I have to read this file :(
public int readData() {
try {
excelFile = new File(excelFullFileName);
fis = new FileInputStream(excelFile);
workBook = new HSSFWorkbook(fis);
if (sheetName != null && !sheetName.equals("")) {
sheet = workBook.getSheet(sheetName);
} else {
sheet = workBook.getSheetAt(0);
sheetName = sheet.getSheetName();
}
sheetRecords.setSheetName(sheetName);
When set workBook catch exception
Exception: org.apache.poi.hssf.record.RecordInputStream$LeftoverDataException: Initialisation of record 0x203(NumberRecord) left 4 bytes remaining still to be read.
If I try to past e copy records on a new xls, java code works fine.
I think it is a file issue, but how I can read original xls file??
Help me please :(

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.

Modifying xlsm document using Java

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.

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