import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtil {
public static void main(String[] args) {
File file = new File("D:\\Tomcat 6\\webapps\\export\\upload\\Book1.xlsx");
try {
List list = readExcel(file);
for (int i = 0; i < list.size(); i++) {
List one = (List) list.get(i);
System.out.println(one.get(0));
System.out.println(one.get(1));
System.out.println(one.get(2));
System.out.println(one.get(3));
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 对外提供读取excel 的方法
* */
public static List> readExcel(File file) throws IOException{
String fileName = file.getName();
String extension = fileName.lastIndexOf(".")==-1 "":fileName.substring(fileName.lastIndexOf(".")+1);
if("xls".equals(extension)){
return read2003Excel(file);
}else if("xlsx".equals(extension)){
return read2007Excel(file);
}else{
throw new IOException("不支持的文件类型");
}
}
/**
* 读取 office 2003 excel
* @throws IOException
* @throws FileNotFoundException */
private static List> read2003Excel(File file) throws IOException{
List> list = new LinkedList
>();
HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet sheet = hwb.getSheetAt(0);
Object value = null;
HSSFRow row = null;
HSSFCell cell = null;
for(int i = sheet.getFirstRowNum();i<= sheet.getPhysicalNumberOfRows();i++){
row = sheet.getRow(i);
if (row == null) {
continue;
}