Thursday, 24 July 2014

Reading and Writing data from excel using 'poi'(xlsx)


Step 1: First u need download 'poi' related all jars and set up these jars files in ur eclipse.
Step 2: just write the below code
//Readig data from excel using poi and writng in to another excel file in java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class DDT_1_Java_Run {

public static void main(String[] args) throws IOException {
File src=new File("TestData.xlsx");
FileInputStream fis=new FileInputStream(src);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet sh=wb.getSheetAt(0);
//getRow specify which row we want to read and getCell which column
System.out.println(sh.getRow(0).getCell(0).getStringCellValue());
System.out.println(sh.getRow(1).getCell(0).getStringCellValue());
sh.getRow(0).createCell(2).setCellValue(11);
sh.getRow(0).createCell(3).setCellValue(12);
FileOutputStream fo=new FileOutputStream("output.xlsx");
wb.write(fo);
fo.close();
}

}
2nd code: using for loop

public class DDT_2_Sele
{

public static void main(String[] args) throws InvalidFormatException, IOException {
// File src=new File("\test\\Test2.xlsx");
// FileInputStream fis=new FileInputStream(src);
Workbook wb=WorkbookFactory.create(new FileInputStream("\test\\Test2.xlsx"));
Sheet sh=wb.getSheetAt(0);
int rows=sh.getLastRowNum();
for(int i=0;i<rows+1;i++)
{
String data1=sh.getRow(i).getCell(0).getStringCellValue();
String data2=sh.getRow(i).getCell(1).getStringCellValue();
System.out.println("Data from 1st column and row:"   +  data1);
System.out.println("Data from 1st column and row:" + data2);
}

}

}

No comments:

Post a Comment