package text;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class readDai {
public static void read(InputStream inputStream) throws IOException{
//初始整个Excel
HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
//循环workbook中所有sheet
for(int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++){
HSSFSheet sheet = workbook.getSheetAt(sheetIndex);
System.out.println("sheet序号:"+sheetIndex+",sheet名称:"+workbook.getSheetName(sheetIndex));
//循环该sheet中的有数据的每一行
for(int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++){
HSSFRow row = sheet.getRow(rowIndex);
if(row == null){
continue;
}
//循环该行的每一个单元格
for(int cellnum = 0; cellnum < row.getLastCellNum(); cellnum++){
HSSFCell cell = row.getCell((short) cellnum);
getCellValue(cell,rowIndex,cellnum);
}
System.out.println();
}
System.out.println("---------------------------------------------------------");
}
}
private static void getCellValue(HSSFCell cell, int rowIndex, int cellnum) {
if(cell == null){
return;
}else if(cell.getCellType() == HSSFCell.CELL_TYPE_BLANK){
System.out.print(" "+"\t");
}else if(cell.getCellType() == HSSFCell.CELL_TYPE_STRING){
System.out.print(cell.getRichStringCellValue().getString()+"\t");
}else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
if(HSSFDateUtil.isCellDateFormatted(cell)){
Date date = cell.getDateCellValue();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.print(dateFormat.format(date)+"\t");
}else{
System.out.print(cell.getNumericCellValue()+"\t");
}
}
else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
System.out.print(cell.getNumericCellValue()+"\t");
}else if(cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN){
System.out.print(cell.getBooleanCellValue()+"\t");
}else if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){
System.out.print(cell.getNumericCellValue()+"\t");
}
return;
}
public static void main(String[] args) {
InputStream inputStream = null;
try {
//读取文件流
inputStream = new FileInputStream(new File("F:\\as.xls"));
read(inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(inputStream != null){
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Java通过poi对Excel的读取操作
最新推荐文章于 2022-12-01 22:18:31 发布