用poi读取excel文件 将文件读取为数据流,然后采用流处理获得文件内容。poi需要引入jar包
写excel文件
public void writeExcel(String filePath,String fileType) throws IOException{
System.out.println("writeExcel");
Workbook wb=null;
if(fileType.equals("xls")){
wb=new HSSFWorkbook();
}
else{
wb=new XSSFWorkbook();
}
Sheet sheet=wb.createSheet("sheet1");
for(int i=0;i<5;i++){
Row row=sheet.createRow(i);
for(int j=0;j<5;j++){
Cell cell=row.createCell(j);
cell.setCellValue("test"+j);
}
}
OutputStream ou=new FileOutputStream(filePath);
wb.write(ou);
ou.close();
}
读excel文件
public void readExcel(String filePath,String fileType) throws IOException{
InputStream in=new FileInputStream(filePath);
Workbook wb=null;
if(fileType.equals("xls")){
wb=new HSSFWorkbook(in);
}
else if(fileType.equals("xlsx")){
wb=new XSSFWorkbook(in);
}
for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
Sheet sheet=wb.getSheetAt(numSheet);
for(int rowNum=0;rowNum<sheet.getLastRowNum();rowNum++){
Row row=sheet.getRow(rowNum);
for(int cellNum=0;cellNum<row.getLastCellNum();cellNum++){
String s=getValue(row.getCell(cellNum));
System.out.println(s);
}
}
}
}