import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public
class ExcelUtil {
private FileOutputStream fos = null;
private FileInputStream fis = null;
private Workbook workbook = null;
private Sheet sheet = null;
private int rowIndex = 0;
private String[]
header ={"Id","Name","Age","Date","Tel","Address"};
public ExcelUtil(){
}
public void InitExcel(String fileName){
try{
workbook = new HSSFWorkbook();
fos = new FileOutputStream(fileName);
sheet = workbook.createSheet("result");
Row headerRow = sheet.createRow(rowIndex);
rowIndex++;
for (short i=0; i<header.length; i++)
{
Cell cell = headerRow.createCell(i);
cell.setCellValue(header[i]);
}
} catch (Exception e){
e.printStackTrace();
}
}
public void WriteRows(HashMap
hash){
try{
Row row = sheet.createRow(rowIndex);
rowIndex++;
Cell cell = null;
int index= 0;
cell = row.createCell(index++);
cell.setCellValue(hash.get("ID")+"");
cell = row.createCell(index++);
cell.setCellValue(hash.get("Name")+"");
cell = row.createCell(index++);
cell.setCellValue(hash.get("Age")+"");
cell = row.createCell(index++);
cell.setCellValue(hash.get("Date")+"");
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
if (hash.get("Date")!=null)
cell.setCellValue(hash.get("Date")+"");
else
cell.setCellType(Cell.CELL_TYPE_BLANK);
cell = row.createCell(index++);
cell.setCellValue(hash.get("Tel")+"");
cell = row.createCell(index++);
cell.setCellValue(hash.get("Address")+"");
}catch(Exception e){
e.printStackTrace();
}
}
public void reader(String fileName){
try{
fis= new FileInputStream(fileName);
Workbook wb = WorkbookFactory.create(fis);
Sheet sheet = wb.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
for (int i=1; i<lastRowNum; i++)
{
Row row = sheet.getRow(i);
int lastColNum = row.getLastCellNum();
Cell cell = row.getCell(0);
if (cell!=null )
{
if (cell.getCellType()== Cell.CELL_TYPE_STRING)
System.out.println(cell.getStringCellValue());
}
cell = row.getCell(1);
if (cell!=null)
{
if (cell.getCellType()==Cell.CELL_TYPE_NUMERIC)
System.out.println(cell.getDateCellValue());
}
cell = row.getCell(2);
if (cell!=null)
{
if (cell.getCellType()== Cell.CELL_TYPE_NUMERIC)
System.out.println(cell.getNumericCellValue());
}
}
}catch(Exception ee){
ee.printStackTrace();
}finally{
try{
fis.close();
}catch(Exception ee){
ee.printStackTrace();
}
fis=null;
}
}
public void finish() {
try{
workbook.write(fos);
}catch(Exception e){
e.printStackTrace();
}finally{
if (fos!=null){
try{
fos.close();
}catch(Exception ee){
ee.printStackTrace();
}
}
fos = null;
}
}
}