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);
Related
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);
}
}
I am trying to read and write data from excel using java selenium webdriver apache poi. But my code is reading data from excel sheet but not write data into excel sheet. I have included all jar files from poi-4.0.1 here is my code
try {
// Specify the file path which you want to create or write
File src=new File("E:\\Dharshan\\test.xlsx");
// Load the file
FileInputStream fis=new FileInputStream(src);
// load the workbook
XSSFWorkbook wb=new XSSFWorkbook(fis);
// get the sheet which you want to modify or create
XSSFSheet sh1= wb.getSheetAt(0);
// getRow specify which row we want to read and getCell which column
System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());
System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());
System.out.println(sh1.getRow(1).getCell(0).getStringCellValue());
System.out.println(sh1.getRow(1).getCell(1).getStringCellValue());
System.out.println(sh1.getRow(2).getCell(0).getStringCellValue());
System.out.println(sh1.getRow(2).getCell(1).getStringCellValue());
// here createCell will create column
// and setCellvalue will set the value
sh1.getRow(0).createCell(3).setCellValue("2.41.0");
sh1.getRow(1).createCell(3).setCellValue("2.5");
sh1.getRow(2).createCell(3).setCellValue("2.39");
// here we need to specify where you want to save file
FileOutputStream fout = new FileOutputStream(src);
wb.write(fout);
fout.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
I am trying to read data from empty excel sheet once i have updated excel sheet with data now it is writing into excel sheet
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 "🔥🔥".
I trying to add new sheet to an existing excel file using Apache poi library as in the below code.
FileOutputStream fileOut = new FileOutputStream(new File(BASE_PATH+outputFile));
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Splitted Rules");
Set<String> tags = outputRules.keySet();
int i = 0;
for (String tag : tags) {
List<String> rules = outputRules.get(tag);
for (String rule : rules) {
Row row = sheet.createRow(i++);
row.createCell(0).setCellValue(tag);
row.createCell(1).setCellValue(rule);
}
}
wb.write(fileOut);
fileOut.close();
wb.close();`
The problem is that all the sheets in the file is deleted and only the new sheets exist.
What is this problem ?
The comments already hint at the solution.
The code above creates a new workbook and overwrites any existing file.
If you want to append a sheet to an existing workbook use the WorkbookFactory.create method (or the XSSFWorkbook constructors with the appropriate argument) to create the workbook based on the existing excel file.
I want to read both xls and xlsx file format. It is working fine for xlsx format but I am getting following error while uploading xls file.
Code:
try {
FileInputStream fileInputStream = new FileInputStream("/apps/" + fileName);
//POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);
Workbook workBook = WorkbookFactory.create(OPCPackage.open(fileInputStream));
//XSSFWorkbook workBook1 = new XSSFWorkbook();
Sheet ssSheet = workBook.getSheetAt(0);
Iterator rowIterator = ssSheet.rowIterator();
while (rowIterator.hasNext()) {
Row ssRow = (Row) rowIterator.next();
Iterator iterator = ssRow.cellIterator();
List cellTempList = new ArrayList();
while (iterator.hasNext()) {
Cell ssCell = (Cell) iterator.next();
cellTempList.add(ssCell);
}
cellDataList.add(cellTempList);
}
} catch (Exception e) {
e.printStackTrace();
}
Error:
org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:148)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:623)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:230)
Please help.
-Thanks
I think that your problem is due to you trying to construct your workbook with the OPCPackage, even if you use WorkbookFactory. OPCPackage "unzip" your .xlsx in order to be able to read the xml files inside, but this should not work for HSSF since it is a binary file.
My recomendation would be that you use another constructor such as
WorkbookFactory.create(InputStream input)
I guess it should work fine.