1.准备好excel如下:
2.编写jsp页面,用于上传文件
< s:form action ="importStudent" method= "post"
enctype ="multipart/form-data" >
导入Excel文件: < s:file name ="importFile" ></ s:file>
< br />
< s:submit value ="导入" ></ s:submit>
</ s:form>
<
s:form
action
=
"importStudent"
method
=
"post"
enctype
=
"multipart/form-data"
>
导入Excel文件:
<
s:file
name
=
"importFile"
></
s:file
>
<
br
/>
<
s:submit
value
=
"导入"
></
s:submit
>
</
s:form
>
2.编写Action,用于解析XML
public class ImportExcelAction extends ActionSupport {
private File importFile ;
private String importFileFileName ;
private List<Student> students ;
public String importStudent() {
try {
if (importFile != null) {
Workbook workBook = this .createWorkbook( new FileInputStream(
importFile ));
if (workBook != null) {
students = new ArrayList<Student>();
for (int i = 0; i < workBook.getNumberOfSheets(); i++) {
Sheet sheet = workBook.getSheetAt(i);
if (sheet != null) {
for (int j = 1; j <= sheet.getLastRowNum(); j++) {
Row row = sheet.getRow(j);
if (row != null) {
Student stu = new Student();
stu.setId(( int ) row.getCell(0)
.getNumericCellValue());
stu.setName(row.getCell(1)
.getStringCellValue());
stu.setAge(( int ) row.getCell(2)
.getNumericCellValue());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-mm-dd" );
stu.setBirth(simpleDateFormat.parse(row
.getCell(3).getStringCellValue()));
students .add(stu);
}
}
}
}
return SUCCESS ;
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return ERROR ;
}
private Workbook createWorkbook(InputStream is) throws IOException {
if (importFileFileName == null || "" .equals(importFileFileName ))
return null ;
if (importFileFileName .endsWith( "xls")) // HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,扩展名是. xls
return new HSSFWorkbook(is);
if (importFileFileName .endsWith( "")) // XSSFWorkbook:是操作Excel2007的版本,扩展名是. xlsx
return new XSSFWorkbook(is);
return null ;
}
public void setImportFile(File importFile) {
this .importFile = importFile;
}
public File getImportFile() {
return importFile ;
}
public void setImportFileFileName(String importFileFileName) {
this .importFileFileName = importFileFileName;
}
public String getImportFileFileName() {
return importFileFileName ;
}
public void setStudents(List<Student> students) {
this .students = students;
}
public List<Student> getStudents() {
return students ;
}
}
3.配置struts的配置文件
< action name ="importStudent" class= "ImportExcelAction" method ="importStudent" >
< result name ="success" > /result.jsp</ result >
< result name ="error" > /error.jsp</ result >
</ action>
4.返回结果如下: