1. 程式人生 > >SpringBoot整合POI實現檔案匯出Excel,匯入Excel更新Mysql資料庫資料

SpringBoot整合POI實現檔案匯出Excel,匯入Excel更新Mysql資料庫資料

        上傳功能 轉載自https://blog.csdn.net/xyy1028/article/details/79054749

原創寫的非常好,但是每個人都有自己的業務邏輯;所以在研究了一點之後,打上註釋,方便新手理解,同時也方便自己記憶;

專案目錄

application.properties檔案

spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password
=admin spring.datasource.driver-class-name=com.mysql.jdbc.Driver ##載入mapper配置檔案 mybatis.mapper-locations=classpath:mapper/*.xml

pom.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
> <modelVersion>4.0.0</modelVersion> <groupId>com.poi</groupId> <artifactId>testpoi</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>testpoi</name> <description>Demo project for Spring Boot</
description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <!--<scope>provided</scope>--> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--熱部署--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency> <!--POI--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

1.自定義異常類

package com.poi.testpoi.common;

public class MyException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    /**
     * 錯誤編碼
*/
private String errorCode;

    /**
     * 訊息是否為屬性檔案中的Key
     */
private boolean propertiesKey = true;

    /**
     * 構造一個基本異常.
     *
     * @param message
*            資訊描述
*/
public MyException(String message)
    {
        super(message);
    }

    /**
     * 構造一個基本異常.
     *
     * @param errorCode
*            錯誤編碼
* @param message
*            資訊描述
*/
public MyException(String errorCode, String message)
    {
        this(errorCode, message, true);
    }

    /**
     * 構造一個基本異常.
     *
     * @param errorCode
*            錯誤編碼
* @param message
*            資訊描述
*/
public MyException(String errorCode, String message, Throwable cause)
    {
        this(errorCode, message, cause, true);
    }

    /**
     * 構造一個基本異常.
     *
     * @param errorCode
*            錯誤編碼
* @param message
*            資訊描述
* @param propertiesKey
*            訊息是否為屬性檔案中的Key
     */
public MyException(String errorCode, String message, boolean propertiesKey)
    {
        super(message);
        this.setErrorCode(errorCode);
        this.setPropertiesKey(propertiesKey);
    }

    /**
     * 構造一個基本異常.
     *
     * @param errorCode
*            錯誤編碼
* @param message
*            資訊描述
*/
public MyException(String errorCode, String message, Throwable cause, boolean propertiesKey)
    {
        super(message, cause);
        this.setErrorCode(errorCode);
        this.setPropertiesKey(propertiesKey);
    }

    /**
     * 構造一個基本異常.
     *
     * @param message
*            資訊描述
* @param cause
*            根異常類(可以存入任何異常)
*/
public MyException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public String getErrorCode()
    {
        return errorCode;
    }

    public void setErrorCode(String errorCode)
    {
        this.errorCode = errorCode;
    }

    public boolean isPropertiesKey()
    {
        return propertiesKey;
    }

    public void setPropertiesKey(boolean propertiesKey)
    {
        this.propertiesKey = propertiesKey;
    }

}

2.IndexController

package com.poi.testpoi.controller;

import com.poi.testpoi.pojo.User;
import com.poi.testpoi.service.UserService;
import com.poi.testpoi.util.ExcelImportUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

   @Autowired
private UserService userService;


   @RequestMapping("/index")
   public String showUser(Model model) {
      List<User> users = userService.selectUsers();
      model.addAttribute("user", users);
      return "index";
   }


   @RequestMapping(value = "/export")
   @ResponseBody
public void export(HttpServletResponse response) throws IOException {
      List<User> users = userService.selectUsers();

      HSSFWorkbook wb = new HSSFWorkbook();

      HSSFSheet sheet = wb.createSheet("獲取excel測試表格");

      HSSFRow row = null;

      row = sheet.createRow(0);//建立第一個單元格
row.setHeight((short) (26.25 * 20));
      row.createCell(0).setCellValue("使用者資訊列表");//為第一行單元格設值
/*為標題設計空間      * firstRow從第1行開始      * lastRow從第0行結束      *
      *從第1個單元格開始      * 從第3個單元格結束      */
CellRangeAddress rowRegion = new CellRangeAddress(0, 0, 0, 2);
      sheet.addMergedRegion(rowRegion);

      /*CellRangeAddress columnRegion = new CellRangeAddress(1,4,0,0);
      sheet.addMergedRegion(columnRegion);*/
      /*
      * 動態獲取資料庫列 sql語句 select COLUMN_NAME from INFORMATION_SCHEMA.Columns where table_name='user' and table_schema='test'
      * 第一個table_name 表名字      * 第二個table_name 資料庫名稱      * */
row = sheet.createRow(1);
      row.setHeight((short) (22.50 * 20));//設定行高
row.createCell(0).setCellValue("使用者Id");//為第一個單元格設值
row.createCell(1).setCellValue("使用者名稱");//為第二個單元格設值
row.createCell(2).setCellValue("使用者密碼");//為第三個單元格設值
for (int i = 0; i < users.size(); i++) {
         row = sheet.createRow(i + 2);
         User user = users.get(i);
         row.createCell(0).setCellValue(user.getUid());
         row.createCell(1).setCellValue(user.getUsername());
         row.createCell(2).setCellValue(user.getPassword());
      }
      sheet.setDefaultRowHeight((short) (16.5 * 20));
      //列寬自適應
for (int i = 0; i <= 13; i++) {
         sheet.autoSizeColumn(i);
      }

      response.setContentType("application/vnd.ms-excel;charset=utf-8");
      OutputStream os = response.getOutputStream();
      response.setHeader("Content-disposition", "attachment;filename=user.xls");//預設Excel名稱
wb.write(os);
      os.flush();
      os.close();


   }


   @RequestMapping(value = "/import")
   public String exImport(@RequestParam(value = "filename")MultipartFile file, HttpSession session) {

      boolean a = false;

      String fileName = file.getOriginalFilename();

      try {
         a = userService.batchImport(fileName, file);
      } catch (Exception e) {
         e.printStackTrace();
      }
      return "redirect:index";
   }
}

3.UserMapper

package com.poi.testpoi.mapper;

import com.poi.testpoi.pojo.User;

import java.util.List;

public interface UserMapper {


   List<User> selectUsers();

   void updateUserByName(User user);

   void addUser(User user);

   int selectByName(String username);
}
 

4.User實體類

package com.poi.testpoi.pojo;

public class User {

   private Integer uid;

   private String username;

   private String password;


   public Integer getUid() {
      return uid;
   }

   public void setUid(Integer uid) {
      this.uid = uid;
   }

   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;
   }  
}

5.UserService

package com.poi.testpoi.service;

import com.poi.testpoi.pojo.User;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

public interface UserService {

   List<User> selectUsers();
   boolean batchImport(String fileName, MultipartFile file) throws Exception;
}

6.UserServiceImpl

package com.poi.testpoi.service.Impl;

import com.poi.testpoi.common.MyException;
import com.poi.testpoi.mapper.UserMapper;
import com.poi.testpoi.pojo.User;
import com.poi.testpoi.service.UserService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {


   @Autowired
private UserMapper userMapper;


   @Override
public List<User> selectUsers() {
      return userMapper.selectUsers();
   }


   @Transactional(readOnly = false,rollbackFor = Exception.class)
   
            
           

相關推薦

SpringBoot整合POI實現檔案匯出Excel匯入Excel更新Mysql資料庫資料

        上傳功能 轉載自https://blog.csdn.net/xyy1028/article/details/79054749原創寫的非常好,但是每個人都有自己的業務邏輯;所以在研究了一點之後,打上註釋,方便新手理解,同時也方便自己記憶;專案目錄applicat

SpringBoot整合poi實現Excel匯入/匯出

新增依賴 <!-- excel匯出工具 --> <dependency> <groupId>org.apache.poi</groupId>

SpringBoot 整合 Thymeleaf 實現增刪改查實現前後端分離做法

通過一個簡單的與Springboot整合Demo認識Thymeleaf模板 文章目錄 通過一個簡單的與Springboot整合Demo認識Thymeleaf模板 什麼是Thymeleaf Thymeleaf 的基礎使用 前後端分離

js-xlsx實現檔案匯出、下載(excel

記錄一下近期使用js-xlsx的一些經驗 真正的.xls\.xlsx檔案,就算是空白的其實是包含了一些內容的 所以並不能直接像寫入txt一樣直接搞一個file往裡面把資料寫入就完了 現在網上查得到匯出excel的一些方法: 1、在IE上使用ActiveXObject匯出檔案 由於我們客戶端是基於

springboot + mybatis + poi實現報表匯出

話不多說,直接上程式碼 資料庫表如下 程式碼結構如下 controller package com.yuanyuan.smp.controller; import java.util.List; import javax.servlet.http.Ht

Springboot整合Rabbitmq實現延時消費實現可靠的訊息處理

一、Rabbitmq簡介1.1 rabbitmq 架構1.2 rabbitmq相關元件介紹exchange: 交換機,主要用來將生產者傳送的訊息路由給伺服器中的佇列。routing-key: 訊息路由的key,生產者在將訊息發到到exchange的時候,需要指定routing

Springboot上傳excel並將表格資料匯入更新mySql資料庫

1.在pom.xml檔案中匯入註解,主要利用POI <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</ar

Springboot/SpringMVC+POI 實現Excel匯出功能(點選下載方式實現

@RequestMapping("/download") public void downstudents(HttpServletRequest request, HttpServletResponse response,@RequestParam String startTime, @Reques

【Java】SpringMVC整合poi實現excel匯入匯出

2.特點:結構: HSSF - 提供讀寫Microsoft Excel格式檔案的功能。 XSSF - 提供讀寫Microsoft Excel OOXML格式檔案的功能。 HWPF - 提供讀寫Microsoft Word格式檔案的功能。 HSLF - 提供讀寫Microsof

SSM 框架整合POI外掛技術匯出EXCEL檔案

前言本次實踐的專案過程當中,對於基於SSM框架實現的專案過程,其中涉及到了前端匯出EXCEL的過程進行整理和彙總,同時對於在網上查詢到的資料等進一步進行解釋和理解,對於網路中的資料,總是會有些不適合自己專案的地方,這個也是大家在學習過程當中會遭遇到,因為別人描述的問題,是他遇

java實現檔案匯出Excel

匯出excel功能: //首先把要匯出檔案的模板放到專案預設的地址下,(也就是webapp地址下) Controller     @RequestMapping("value="")     //匯出方法    &nbs

JFileChooser實現檔案匯出匯入Excel

最近在做一個檔案匯入匯出到Excel的專案模組,做了一個簡單的Demo,放在這裡。 注:對Excel的操作使用的是poi.jar包; package jfile; import java.io.File; import java.io.FileInputStream; i

springBoot整合POI匯入Excel

        //獲取一共有多少sheet,遍歷int numberOfSheets = book.getNumberOfSheets();        for (int i=0; i<numberOfSheets; i++) {            Sheet sheet = book.getS

springboot整合websocket實現頁面線上客服聊天並且解決無法注入例項的問題

本文采用現在流行的springboot框架整合websocket實現線上客服的聊天功能,程式碼實現如下:pom.xml:<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.

SpringBoot整合Mybatis自定義攔截器實現拼接sql和修改

一、應用場景 1.分頁,如com.github.pagehelper的分頁外掛實現; 2.攔截sql做日誌監控; 3.統一對某些sql進行統一條件拼接,類似於分頁。 二、MyBatis的攔截器簡介 然後我們要知道攔截器攔截什麼樣的物件,攔截物件的什麼行為,什麼時候攔截? &n

POI實現java匯出Excel功能

import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel

springboot整合easyexcel實現Excel導入導出

ray tro set time 級別 批量創建 boot ont 上下文 easyexcel:快速、簡單避免OOM的java處理Excel工具 Java解析、生成Excel比較有名的框架有Apache poi、jxl。但他們都存在一個嚴重的問題就是非常的耗內存,poi有

SpringBoot整合easyexcel實現Excel匯入

上篇寫了Excel如何匯出,那麼其實在提供的那幾個工具類中已經有了匯入的方法,只需要直接呼叫即可。下面我們來簡單演示一下,如何匯入

SpringBoot 4.SpringBoot 整合 devtools 實現熱部署

exce 機制 maven optional 引入 實現 目錄 觸發 exclude 一、添加 devtools 依賴 <!-- Spring boot 熱部署 : 此熱部署會遇到 java.lang.ClassCastException 異常 --

SpringBoot整合Mybatis實現增刪改查的功能

ger 開始 pan ble img 映射 講師 -name date SpringBoot框架作為現在主流框架之一,好多框架都漸漸的移植到SpringBoot中來。前面我給大家介紹過redis,jpa等等的的整合,今天在這裏給大家介紹一下Mybatis的整合過程。 S