需要引入poi的相关jar包即可。
1.ExcelHandle 判断Excel的格式
import java.io.File;
import java.io.FileInputStream;import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelHandle {
private static final String EXCEL_XLS = "xls";
private static final String EXCEL_XLSX = "xlsx";
/**
* Judging the version of Excel
* @param in
* @param filename
* @return
* @throws IOException
*/
public static Workbook getWorkbook(File file) throws IOException{
Workbook wb = null;
FileInputStream in = new FileInputStream(file);
if(file.getName().endsWith(EXCEL_XLS)){ //Excel 2003
wb = new HSSFWorkbook(in);
System.out.println("Excel file type:xls");
}else if(file.getName().endsWith(EXCEL_XLSX)){ // Excel 2007/2010
wb = new XSSFWorkbook(in);
System.out.println("Excel file type:xlsx");
}
return wb;
}
}
2.ParseExcel用来解析Excel,一行一行读取
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;
public class ParseExcel{
/**
* Read Excel test, compatible with Excel 2003/2007/2010
* @throws Exception
*/
public static v