第一次擼項目偿渡,使用SSM框架臼寄,需要用Excel導入學生信息,花了很長的時間卸察,特此記錄下來脯厨,分享給大家铅祸,有什么問題希望不要見怪坑质,本人是剛入門的小白。
首先看一項目結構
image
一临梗、pojo下定義兩個實體類涡扼,一個是對于excel文件,解析它的數據(ExcelBean)盟庞,另一個是導入數據庫表的實體類(student)
ExcelBean.java
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
public class ExcelBean implements java.io.Serializable {
private String headTextName;//列頭(標題)名
private String propertyName;//對應字段名
private Integer cols;//合并單元格數
private XSSFCellStyle cellStyle;
public ExcelBean(){
}
public ExcelBean(String headTextName, String propertyName){
this.headTextName = headTextName;
this.propertyName = propertyName;
}
public ExcelBean(String headTextName, String propertyName, Integer cols) {
super();
this.headTextName = headTextName;
this.propertyName = propertyName;
this.cols = cols;
}
public String getHeadTextName() {
return headTextName;
}
public void setHeadTextName(String headTextName) {
this.headTextName = headTextName;
}
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
public Integer getCols() {
return cols;
}
public void setCols(Integer cols) {
this.cols = cols;
}
public XSSFCellStyle getCellStyle() {
return cellStyle;
}
public void setCellStyle(XSSFCellStyle cellStyle) {
this.cellStyle = cellStyle;
}
}
student.java
public class Student {
//用戶id
private Long id;
//用戶登錄名
private String username;
//用戶密碼
private String password;
private String classname;
private String num;
public Long getId(String stringCellValue) {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public void setUserName(String valueOf) {
this.username = username == null ? null : username.trim();
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
}
二吃沪、定義mapper文件(SSM里面就是這種結構,相當于DAO文件一樣)什猖。
StudentMapper.java
public interface StudentMapper {
Student login(String username);
int deleteByPrimaryKey(Long id);
int insert(Student record);
int insertSelective(Student record);
Student selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(Student record);
int updateByPrimaryKey(Student record);
void insertInfoBatch(List<Student> list);
}
StudentMapper.xml
<mapper namespace="cn.ds.mapper.StudentMapper">
<resultMap type="cn.ds.pojo.Student" id="BaseResultMap">
<id column="id" property="id" />
<result column="username" property="username" />
<result column="password" property="password" />
<result column="classname" property="classname" />
<result column="num" property="num" />
</resultMap>
<sql id="Base_Column_List" >
id, username, password,classname,num
</sql>
<!-- 用戶登錄的方法 id與方法名中相同 持久層-->
<select id="login" parameterType="cn.ds.pojo.Student" resultType="Student">
select * from student where username = #{username}
</select>
<insert id="insertInfoBatch" parameterType="java.util.List">
insert into student (id, username, password,classname,num)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{id,jdbcType=INT},
#{userName,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR} ,
#{classname,jdbcType=VARCHAR},
#{num,jdbcType=VARCHAR})
</foreach>
</insert>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Long" >
select *from student
where id = #{id}
</select>
<insert id="insert" parameterType="cn.ds.pojo.Student" >
insert into Student (id, username, password,classname,num)
values (#{id}, #{username}, #{password},
#{classname}, #{num})
</insert>
<update id="updateByPrimaryKey" parameterType="cn.ds.pojo.Student" >
update student
set username = #{username},
password = #{password},
classname = #{classname},
num = #{num}
where id = #{id}
</update>
</mapper>
三票彪、util下ExcelUtils工具類(也就是解析EXCEL文件红淡,判斷EXCEL的類型以及數據的類型)
public class ExcelUtils {
private final static Stringexcel2003L =".xls"; //2003- 版本的excel
private final static Stringexcel2007U =".xlsx"; //2007+ 版本的excel
/**
* 描述:獲取IO流中的數據,組裝成List<List<Object>>對象
* @param in,fileName
* @return
* @throws IOException
*/
public List>getBankListByExcel(InputStream in,String fileName)throws Exception{
List> list =null;
//創(chuàng)建Excel工作薄
Workbook work =this.getWorkbook(in,fileName);
if(null == work){
throw new Exception("創(chuàng)建Excel工作薄為空降铸!");
}
Sheet sheet =null; //頁數
Row row =null; //行數
Cell cell =null; //列數
list =new ArrayList>();
//遍歷Excel中所有的sheet
for (int i =0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet==null){continue;}
//遍歷當前sheet中的所有行
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
row = sheet.getRow(j);
if(row==null||row.getFirstCellNum()==j){continue;}
//遍歷所有的列
List li =new ArrayList();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(this.getValue(cell));
}
list.add(li);
}
}
return list;
}
/**
* 描述:根據文件后綴在旱,自適應上傳文件的版本
* @param inStr,fileName
* @return
* @throws Exception
*/
public WorkbookgetWorkbook(InputStream inStr,String fileName)throws Exception{
Workbook wb =null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(excel2003L.equals(fileType)){
wb =new HSSFWorkbook(inStr); //2003-
}else if(excel2007U.equals(fileType)){
wb =new XSSFWorkbook(inStr); //2007+
}else{
throw new Exception("解析的文件格式有誤!");
}
return wb;
}
/**
* 描述:對表格中數值進行格式化
* @param cell
* @return
*/
//解決excel類型問題推掸,獲得數值
public StringgetValue(Cell cell) {
String value ="";
if(null==cell){
return value;
}
switch (cell.getCellType()) {
//數值型
case Cell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
//如果是date類型則 桶蝎,獲取該cell的date值
Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd");
value = format.format(date);;
}else {// 純數字
BigDecimal big=new BigDecimal(cell.getNumericCellValue());
value = big.toString();
//解決1234.0 去掉后面的.0
if(null!=value&&!"".equals(value.trim())){
String[] item = value.split("[.]");
if(1
value=item[0];
}
}
}
break;
//字符串類型
case Cell.CELL_TYPE_STRING:
value = cell.getStringCellValue().toString();
break;
// 公式類型
case Cell.CELL_TYPE_FORMULA:
//讀公式計算值
value = String.valueOf(cell.getNumericCellValue());
if (value.equals("NaN")) {// 如果獲取的數據值為非法值,則轉換為獲取字符串
value = cell.getStringCellValue().toString();
}
break;
// 布爾類型
case Cell.CELL_TYPE_BOOLEAN:
value =" "+ cell.getBooleanCellValue();
break;
default:
value = cell.getStringCellValue().toString();
}
if("null".endsWith(value.trim())){
value="";
}
return value;
}
}
四、實現(xiàn)service接口
StudentServiceImpl.java
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentmapper;
public String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response){
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");
System.out.println("得到數據文件");
if(file.isEmpty()){
try {
throw new Exception("文件不存在谅畅!");
} catch (Exception e) {
e.printStackTrace();
}
}
InputStream in =null;
try {
in = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("加載流");
List<List<Object>> listob = null;
try {
System.out.println("加載流");
listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
}
//該處可調用service相應方法進行數據保存到數據庫中登渣,現(xiàn)只對數據輸出
for (int i = 0; i < listob.size(); i++) {
List<Object> lo = listob.get(i);
System.out.println("遍歷" + listob.get(i));
Student vo = new Student();
Student j = null;
try {
//j = studentmapper.selectByPrimaryKey(Long.valueOf());
j = studentmapper.selectByPrimaryKey(Long.valueOf(String.valueOf(lo.get(0))));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
System.out.println("沒有新增");
}
vo.setId(Long.valueOf(String.valueOf(lo.get(0))));
vo.setUsername(String.valueOf(lo.get(1)));
vo.setPassword(String.valueOf(lo.get(2)));
vo.setClassname(String.valueOf(lo.get(3)));
vo.setNum(String.valueOf(lo.get(4)));
if(j == null)
{
studentmapper.insert(vo);
}
else
{
studentmapper.updateByPrimaryKey(vo);
}
}
return "success";
}
}
五、控制層Controller
StudentController.java
@ResponseBody
@RequestMapping(value="ajaxUpload",method={RequestMethod.GET,RequestMethod.POST})
public String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {
System.out.println("這是請求");
return studentService.ajaxUploadExcel(request, response);
}
六毡泻、jsp頁面
<form action="<%=basePath%>/student/ajaxUpload.do" method="post" enctype="multipart/form-data">
請選擇Excel:<input type="file" name="file">
<input type="submit" name="提交">
</form>
七胜茧、實現(xiàn)圖片
image.png
image.png
image.png