Apache POI: Save unicodes to xslx file - java

How to save symbols like 🔥🔥 to xlsx file using Java 8 and Apache POI library?
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("\uD83D\uDD25\uD83D\uDD25");
try {
FileOutputStream outputStream = new FileOutputStream("text.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
As a result, I get a file with symbols "????" Instead of "🔥🔥".

Related

Write in Excel from Java NoClassDefFoundError

When I try to add data to Excel from Java Ant, it shows NoClassDefFoundError, even that I imported all Jar files of Apache Poi. This is the Error:
Exception in thread "main" java.lang.NoClassDefFoundError:org/apache/commons/io/output/UnsynchronizedByteArrayOutputStream
This is the code i tried:
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("Sheet1");
XSSFRow row = sheet.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("HelloWorld!");
try{
FileOutputStream out = new FileOutputStream(new File("Result.xlsx"));
wb.write(out);
out.close();
System.out.println("Done");
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
These are Jar imported files:
Problem solved! It seems i needed to add dependecy to build.xml also after importing jar files!

Apache POI creating corrupt XLSX files

I'm trying to create a simple Excel file in XLSX format.
I can create the old XLS files but when I try to create the other format, the file is always corrupt.
I'm using Apache POI 4.1.1.
This is my simple code:
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
FileOutputStream fo = new FileOutputStream("C:/Users/Public/invoice_file/Test.xlsx");
try {
wb.write(fo);
fo.flush();
fo.close();
wb.close();
}catch (Exception e) {
e.printStackTrace();
}
And this is the error message: Error
Use
org.apache.poi.ss.usermodel.WorkbookFactory
//Parameter indicates whether you want to create an XSSF formatted file or not
WorkbookFactory.create(true); //true creates XSSF formatted file
will return you an instance of
org.apache.poi.ss.usermodel.Workbook
Then you can write to the file using
Workbook.write(OutputStream)
Solution:
try (Workbook wb = WorkbookFactory.create(true)) {
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
try (FileOutputStream fos = new FileOutputStream("D:/Test.xlsx")) {
wb.write(fos);
}
}

Create .csv file with Apache POI doesn't work

I need to create a file .csv with apache-poi but this file is empty. For this example I want to create only header about this file so I do:
public byte[]...(File save_file) {
Workbook workbook = null;
Sheet sheet = null;
FileOutputStream outputStream=null;
try {
workbook = new HSSFWorkbook();
sheet = workbook.createSheet();
createHeader(0,sheet);
outputStream = new FileOutputStream(save_file);
workbook.write(outputStream);
} catch (Exception exception) {
log.error("ERROR", exception);
} finally {
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.writeTo(outputStream);
log.info("SOTTO BYTE "+byteArrayOutputStream.toByteArray().length);
return byteArrayOutputStream.toByteArray();
}
and after the method "create_header":
private static void createHeader(int rowPosition,Sheet sheet) {
Row row = sheet.createRow(rowPosition);
Cell cell = row.createCell(1);
cell.setCellValue("DATE");
cell = row.createCell(2);
cell.setCellValue("EMAIL");
}
The problem is the file is empty. In the first method I need to return the byte[] that represents the csv file. Anyone can help me?

Read / Write different Microsoft Office file formats using Apache POI

How to perform different functions on Microsoft Excel spreadsheet using Apache POI ?
I'm trying to generate and update an Excel file ( data from DB ) from my Spring MVC App..
Thanks
Include apache poi jar file
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
To read an excel file
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//..
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();
The classes we used in above code snippet, HSSFWorkbook and HSSFSheet works for .xls format. In order to work with .xlsx use XSSFWorkbook and XSSFSheet class.
Similar to HSSF, POI has different prefix for other file formats too:
HSSF (Horrible SpreadSheet Format) – reads and writes Microsoft Excel (XLS) format files.
XSSF (XML SpreadSheet Format) – reads and writes Office Open XML (XLSX) format files.
HPSF (Horrible Property Set Format) – reads “Document Summary” formation from Microsoft Office files.
HWPF (Horrible Word Processor Format) – aims to read and write Microsoft Word 97 (DOC) format files.
HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft PowerPoint files.
HDGF (Horrible DiaGram Format) – an initial pure Java implementation for Microsoft Visio binary files.
HPBF (Horrible PuBlisher Format) – a pure Java implementation for Microsoft Publisher files.
HSMF (Horrible Stupid Mail Format) – a pure Java implementation for Microsoft Outlook MSG files.
DDF (Dreadful Drawing Format) – a package for decoding the Microsoft Office Drawing format.
Create New Excel File
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//..
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FuSsA sheet");
//Create a new row in current sheet
Row row = sheet.createRow(0);
//Create a new cell in current row
Cell cell = row.createCell(0);
//Set value to new value
cell.setCellValue("Slim Shady");
try {
FileOutputStream out =
new FileOutputStream(new File("C:\\new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Update Existing Excel File
try {
FileInputStream file = new FileInputStream(new File("C:\\update.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = null;
//Update the value of cell
cell = sheet.getRow(1).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
cell = sheet.getRow(2).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
cell = sheet.getRow(3).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
file.close();
FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
For more details, Adding Formulas and Adding Styles to Cell you can check this link: Read / Write Excel file in Java using Apache POI
For manipulation of any cells or adding formula , you can use the folowing:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Calculate Simple Interest");
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("Pricipal Amount (P)");
header.createCell(1).setCellValue("Rate of Interest (r)");
header.createCell(2).setCellValue("Tenure (t)");
header.createCell(3).setCellValue("Interest (P r t)");
Row dataRow = sheet.createRow(1);
dataRow.createCell(0).setCellValue(14500d);
dataRow.createCell(1).setCellValue(9.25);
dataRow.createCell(2).setCellValue(3d);
dataRow.createCell(3).setCellFormula("A2*B2*C2");
try {
FileOutputStream out =
new FileOutputStream(new File("C:\\formula.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
For adding styles to the cell,
you can use: cell.setCellStyle(style);
For adding background to cells, you can use the following:
cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

Error in getting data from excel: Invalid header signature

I am trying to read a .xlsx Excel file but I am getting an exception:
Error in getting data from excel Invalid header signature; read
1688935826934608, expected -2226271756974174256
What is the thing that I am missing?
My code is
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(filePath + "\\"
+ "uploadAreaExcel.xlsx");
HSSFWorkbook workbook;
workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet("Sheet1");
System.out.println("Total Count :"
+ Integer.toString(worksheet.getLastRowNum()));
for(int i=1;i<worksheet.getLastRowNum();i++){
HSSFRow row1 = worksheet.getRow(i);
HSSFCell cellA1 = row1.getCell((short) 0);
System.out.println(cellA1.getStringCellValue());
HSSFCell cellB1 = row1.getCell((short) 1);
System.out.println(cellB1.getStringCellValue());
}
} catch (Exception e) {
System.out.println("Error in getting data from excel "+e.getMessage());
}
Ok, now I see that you are using HSSF to handle .xlsx file. But HSSF doesn't support .xlsx, you should give a try to XSSF workbook.

Categories