页面部分
<form method="post" name ="test" enctype="multipart/form-data">
<input type="file" name="file"/>
</form>
实体类部分
public Class Test{
private String id;
private String name;
private String address;
//以下为get、set方法(省略)
}
Action部分
按照strusts2获取file
private File file;
private String fileName;
private String fileContentType;
添加get、set方法
//获取workBook对象
XSSFWorkbook workBook = new XSSFWorkbook(file.getInputStream());
//定义workSheet
XSSFSheet workSheet = null;
//定义从excel获取的数据拼接成一个List对象
List<Test> listTest=new ArrayList<Test>();
//获取sheet页数量
int sheetCount = workBook.getNumberOfSheets();
for(int i=0;i<sheetCount;i++){
//获取第i个sheet
workSheet = workBook.getSheetAt(i);
//获取该sheet页的行数
for(int j=0;j<workSheet.getPhysicalNumberOfRows(); j++){
//获取第j行
XSSFRow row = workSheet.getRow(j);
Test test=new Test();
//row.getCell(0)获取第j行第1个单元格的数据
test.setId(row.getCell(0)==null ? "":row.getCell(0).toString().trim());
//判断 如果第2行为数字格式 转成字符串
if(row.getCell(1) !=null && row.getCell(1).getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
}
test.setName(row.getCell(1)==null ? "":row.getCell(1).toString().trim());
test.setAddress(row.getCell(2)==null ? "":row.getCell(2).toString().trim());
listTest.add(test);
}
}
ibatis部分
<insert id="export" parameterClass="java.util.List">
<![CDATA[
insert all
]]>
<iterate conjunction=" ">
<![CDATA[
into test(id,name,address)
values
(#listTest[].id#,#listTest[].name#,#listTest[].address#)
]]>
</iterate>
<![CDATA[
select 1 from dual
]]>
</insert>