POI Sample Applications
2. Reading from Excel sheet :
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ReadExcel{
public static String fileTobeRead = "D:/work/java-excel.xls";
public static void main(String[] args){
try{
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileTobeRead));
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
HSSFCell cell = row.getCell((short)0);
System.out.prinntln("The top left cell -->"+ cell.getRichStringCellValue());
}catch(Exception e){
e.printStackTrace();
}
}
}
3. Reading & Writing MS Word document using java :
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.extractor.wordExtractor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class ReadWord{
private static String fileName= "d:/work/sample.doc";
public static void main(String[] args){
ReadWord rdWord new ReadWord();
rdWord.createWord();
rdWord.readWord();
}
// Writing into MSWord
public void createWord(){
try{
POFSFileSystem out = new POIFSFileSystem(new FileInputStream(fileName));
HWPFDocument doc = new HWPFDocument(out);
Range range = doc.getRange();
range.insertBefore("hai rams");
FileOutputStream fout = new FileOutputStream(fileName);
doc.write(fout);
}catch(Exception e){
e.printStackTrace();
}
}
// Reading From MSWord
public void readWord(){
try{
POFSFileSystem fs = new POIFSFileSystem(new FileInputStream(fileName));
HWPFDocument doc = new HWPFDocument(fs);
WordExtractor we = new WordExtractor(do);
String para = we.getTextFromPices();
System.out.println("No of letters ------"+ para.length());
System.out.println(" data ------------"+para);
}catch(Exception e){
e.printStackTrace();
}
}
}