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
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 know i am missing the main function here. I want to copy/ write only particular row from my source excel to destination excel using apache POI.
eg. My source excel has 10 rows. I need only 5th row to be copied to my destination excel.
My class,
public class Test1 {
public static void main(String[] args) throws Exception{
File srcFile=new File("C:\\Test\\Read.xlsx");
FileInputStream fis=new FileInputStream(srcFile);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet sheet1=wb.getSheetAt(0);
File desFile=new File("C:\\Test\\Write.xlsx");
FileOutputStream fout=new FileOutputStream(desFile);
wb.write(fout);
wb.close();
}
}
As per the Apache POI docs, you can use the XSSFSheet.getRow(int) method to get a row at a specific index.
// 5th row
Row row = sheet.getRow(4);
To add this row to a new workbook, you'll have to iterate through each cell in the row object and set the value of cells in the new workbook to these values. An example can be found here.
Following is the peace of code which i'm trying to read large excel sheet in to java level. This code works fine when my excel sheet input is small. But when I'm trying to read large excel sheet (size is about 5MB and 100000 records) it return a exception
java.io.IOException: inputstream is closed
try {
InputStream excelFile = new FileInputStream(excel);
XSSFWorkbook workbook =new XSSFWorkbook(excelFile);
if(excelFile!=null){
excelFile.close();
}
} catch (Exception e) {
e.printStackTrace();
}
what is the reason for that? Is there any alternative ways to read large excel sheets in 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);
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.