ssm解析excel表导入数据到数据库

待我称王封你为后i 2022-05-15 00:53 454阅读 0赞

1、maven配置相应jar

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version>3.8-beta3</version>
  5. <type>jar</type>
  6. <scope>compile</scope>
  7. </dependency>
  8. <dependency>
  9. <groupId>org.apache.poi</groupId>
  10. <artifactId>poi-ooxml</artifactId>
  11. <version>3.9</version>
  12. <type>jar</type>
  13. </dependency>

2、创建excel工具类文件ExcelUtils

  1. import java.io.IOException;
  2. import java.io.InputStream;
  3. import java.math.BigDecimal;
  4. import java.text.SimpleDateFormat;
  5. import java.util.ArrayList;
  6. import java.util.Date;
  7. import java.util.List;
  8. import org.apache.poi.hssf.usermodel.HSSFDateUtil;
  9. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  10. import org.apache.poi.ss.usermodel.Cell;
  11. import org.apache.poi.ss.usermodel.Row;
  12. import org.apache.poi.ss.usermodel.Sheet;
  13. import org.apache.poi.ss.usermodel.Workbook;
  14. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  15. public class ExcelUtils {
  16. private final static String excel2003L =".xls"; //2003- 版本的excel
  17. private final static String excel2007U =".xlsx"; //2007+ 版本的excel
  18. /** * 描述:获取IO流中的数据,组装成List<List<Object>>对象 * @param in,fileName * @return * @throws IOException */
  19. public List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
  20. List<List<Object>> list = null;
  21. //创建Excel工作薄
  22. Workbook work = this.getWorkbook(in,fileName);
  23. if(null == work){
  24. throw new Exception("创建Excel工作薄为空!");
  25. }
  26. Sheet sheet = null; //页数
  27. Row row = null; //行数
  28. Cell cell = null; //列数
  29. list = new ArrayList<List<Object>>();
  30. //遍历Excel中所有的sheet
  31. for (int i = 0; i < work.getNumberOfSheets(); i++) {
  32. sheet = work.getSheetAt(i);
  33. if(sheet==null){
  34. continue;}
  35. //遍历当前sheet中的所有行
  36. for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
  37. row = sheet.getRow(j);
  38. if(row==null||row.getFirstCellNum()==j){
  39. continue;}
  40. //遍历所有的列
  41. List<Object> li = new ArrayList<Object>();
  42. for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
  43. cell = row.getCell(y);
  44. li.add(this.getValue(cell));
  45. }
  46. list.add(li);
  47. }
  48. }
  49. return list;
  50. }
  51. /** * 描述:根据文件后缀,自适应上传文件的版本 * @param inStr,fileName * @return * @throws Exception */
  52. public Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
  53. Workbook wb = null;
  54. String fileType = fileName.substring(fileName.lastIndexOf("."));
  55. if(excel2003L.equals(fileType)){
  56. wb = new HSSFWorkbook(inStr); //2003-
  57. }else if(excel2007U.equals(fileType)){
  58. wb = new XSSFWorkbook(inStr); //2007+
  59. }else{
  60. throw new Exception("解析的文件格式有误!");
  61. }
  62. return wb;
  63. }
  64. /** * 描述:对表格中数值进行格式化 * @param cell * @return */
  65. //解决excel类型问题,获得数值
  66. public String getValue(Cell cell) {
  67. String value = "";
  68. if(null==cell){
  69. return value;
  70. }
  71. switch (cell.getCellType()) {
  72. //数值型
  73. case Cell.CELL_TYPE_NUMERIC:
  74. if (HSSFDateUtil.isCellDateFormatted(cell)) {
  75. //如果是date类型则 ,获取该cell的date值
  76. Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
  77. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  78. value = format.format(date);;
  79. }else {
  80. // 纯数字
  81. BigDecimal big=new BigDecimal(cell.getNumericCellValue());
  82. value = big.toString();
  83. //解决1234.0 去掉后面的.0
  84. if(null!=value&&!"".equals(value.trim())){
  85. String[] item = value.split("[.]");
  86. if(1<item.length&&"0".equals(item[1])){
  87. value=item[0];
  88. }
  89. }
  90. }
  91. break;
  92. //字符串类型
  93. case Cell.CELL_TYPE_STRING:
  94. value = cell.getStringCellValue().toString();
  95. break;
  96. // 公式类型
  97. case Cell.CELL_TYPE_FORMULA:
  98. //读公式计算值
  99. value = String.valueOf(cell.getNumericCellValue());
  100. if (value.equals("NaN")) {
  101. // 如果获取的数据值为非法值,则转换为获取字符串
  102. value = cell.getStringCellValue().toString();
  103. }
  104. break;
  105. // 布尔类型
  106. case Cell.CELL_TYPE_BOOLEAN:
  107. value = " "+ cell.getBooleanCellValue();
  108. break;
  109. default:
  110. value = cell.getStringCellValue().toString();
  111. }
  112. if("null".endsWith(value.trim())){
  113. value="";
  114. }
  115. return value;
  116. }
  117. }

3、实体类people.java

  1. public class people {
  2. private Integer id;
  3. private String userName;
  4. private String password;
  5. public Integer getId() {
  6. return id;
  7. }
  8. public void setId(Integer id) {
  9. this.id = id;
  10. }
  11. public String getUserName() {
  12. return userName;
  13. }
  14. public void setUserName(String userName) {
  15. this.userName = userName == null ? null : userName.trim();
  16. }
  17. public String getPassword() {
  18. return password;
  19. }
  20. public void setPassword(String password) {
  21. this.password = password == null ? null : password.trim();
  22. }
  23. }

4、创建peopleMapper.java

  1. public interface peopleMapper {
  2. int deleteByPrimaryKey(Integer id);
  3. int insert(people record);
  4. int insertSelective(people record);
  5. people selectByPrimaryKey(Integer id);
  6. int updateByPrimaryKeySelective(people record);
  7. int updateByPrimaryKey(people record);
  8. void insertInfoBatch(List<people> list);
  9. }

peopleMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3. <mapper namespace="cn.com.vtech.dao.peopleMapper" >
  4. <resultMap id="BaseResultMap" type="cn.com.entity.people" >
  5. <id column="id" property="id" jdbcType="INTEGER" />
  6. <result column="username" property="userName" jdbcType="VARCHAR" />
  7. <result column="password" property="password" jdbcType="VARCHAR" />
  8. </resultMap>
  9. <sql id="Base_Column_List" >
  10. id, username, password
  11. </sql>
  12. <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
  13. select
  14. <include refid="Base_Column_List" />
  15. from people
  16. where id = #{id,jdbcType=INTEGER}
  17. </select>
  18. <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
  19. delete from people
  20. where id = #{id,jdbcType=INTEGER}
  21. </delete>
  22. <insert id="insert" parameterType="cn.com.vtech.entity.people" >
  23. insert into people (id, username, password)
  24. values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR})
  25. </insert>
  26. <insert id="insertSelective" parameterType="cn.com.vtech.entity.people" >
  27. insert into people
  28. <trim prefix="(" suffix=")" suffixOverrides="," >
  29. <if test="id != null" >
  30. id,
  31. </if>
  32. <if test="userName != null" >
  33. username,
  34. </if>
  35. <if test="password != null" >
  36. password,
  37. </if>
  38. </trim>
  39. <trim prefix="values (" suffix=")" suffixOverrides="," >
  40. <if test="id != null" >
  41. #{id,jdbcType=INTEGER},
  42. </if>
  43. <if test="userName != null" >
  44. #{userName,jdbcType=VARCHAR},
  45. </if>
  46. <if test="password != null" >
  47. #{password,jdbcType=VARCHAR},
  48. </if>
  49. </trim>
  50. </insert>
  51. <update id="updateByPrimaryKeySelective" parameterType="cn.com.vtech.entity.people" >
  52. update people
  53. <set >
  54. <if test="userName != null" >
  55. user_name = #{userName,jdbcType=VARCHAR},
  56. </if>
  57. <if test="password != null" >
  58. password = #{password,jdbcType=VARCHAR},
  59. </if>
  60. </set>
  61. where id = #{id,jdbcType=INTEGER}
  62. </update>
  63. <update id="updateByPrimaryKey" parameterType="cn.com.vtech.entity.people" >
  64. update people
  65. set username = #{userName,jdbcType=VARCHAR},
  66. password = #{password,jdbcType=VARCHAR}
  67. where id = #{id,jdbcType=INTEGER}
  68. </update>
  69. <insert id="insertInfoBatch" parameterType="java.util.List">
  70. insert into people (id, username, password)
  71. values
  72. <foreach collection="list" item="item" index="index" separator=",">
  73. (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR})
  74. </foreach>
  75. </insert>
  76. </mapper>

5、service层
创建peopleService.java

  1. public interface PeopleService {
  2. String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response);
  3. }

创建peopleServiceImpl.java

  1. @Service("PeopleService")
  2. public class PeopleServiceImpl implements PeopleService{
  3. @Resource(name="peopleMapper")
  4. private peopleMapper peopleMapper;
  5. public String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response){
  6. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  7. MultipartFile file = multipartRequest.getFile("file");
  8. if(file.isEmpty()){
  9. try {
  10. throw new Exception("文件不存在!");
  11. } catch (Exception e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. InputStream in =null;
  16. try {
  17. in = file.getInputStream();
  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. }
  21. List<List<Object>> listob = null;
  22. try {
  23. listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. }
  27. for (int i = 0; i < listob.size(); i++) {
  28. /* List<Object> lo = listob.get(i); if (lo.get(i)=="") { continue; }*/
  29. System.out.println(listob.get(i));
  30. }
  31. for (int i = 0; i < listob.size(); i++) {
  32. List<Object> lo = listob.get(i);
  33. people vo = new people();
  34. people j = null;
  35. try {
  36. j = peopleMapper.selectByPrimaryKey(Integer.valueOf(String.valueOf(lo.get(0))));
  37. } catch (NumberFormatException e) {
  38. // TODO Auto-generated catch block
  39. System.out.println("数据库中无该条数据,新增");
  40. }
  41. vo.setId(Integer.valueOf(String.valueOf(lo.get(0))));
  42. vo.setUserName(String.valueOf(lo.get(1)));
  43. vo.setPassword(String.valueOf(lo.get(2)));
  44. if(j == null)
  45. {
  46. peopleMapper.insert(vo);
  47. System.out.println("susscess");
  48. }
  49. else
  50. {
  51. peopleMapper.updateByPrimaryKey(vo);
  52. }
  53. }
  54. return "文件导入成功!";
  55. }
  56. }

6、Contrller层
创建ExcelController.java

  1. @Controller
  2. @RequestMapping("/upload")
  3. public class ExcelController {
  4. @Resource(name="PeopleService")
  5. private PeopleService PeopleService;
  6. @ResponseBody
  7. @RequestMapping(value="ajaxUpload.do",method={RequestMethod.GET,RequestMethod.POST})
  8. public String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {
  9. return PeopleService.ajaxUploadExcel(request, response);
  10. }

7、前端页面
前端使用的是layui,此处贴出关键代码

  1. <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
  2. <legend>选完文件后不自动上传</legend>
  3. </fieldset>
  4. <div class="layui-upload">
  5. <button type="button" class="layui-btn layui-btn-normal" id="test8">选择文件</button>
  6. <button type="button" class="layui-btn" id="test9">开始上传</button>
  7. </div>
  8. <script type="text/javascript" src="../../layui/layui.js"></script>
  9. <script type="text/javascript" src="../../js/jquery-3.2.1.min.js" ></script>
  10. <!--<script type="application/javascript" src="../../js/rfq_header.js"></script>-->
  11. <script> layui.use('upload', function(){ var $ = layui.jquery ,upload = layui.upload; var url=path+'uploadExcel/ajaxUpload.do'; //选完文件后不自动上传 upload.render({ elem: '#test8' ,url: url ,auto: false ,accept:"file" //指定允许上传的文件类型 //,multiple: true ,bindAction: '#test9' ,done: function(res){ console.log("上传成功") } }); }); </script>

8、excel表中格式

  1. ID USERNAME PASSWORD
  2. 3 rr rr123
  3. 4 jj2 jjp

发表评论

表情:
评论列表 (有 0 条评论,454人围观)

还没有评论,来说两句吧...

相关阅读