jsp頁面:
<form enctype="multipart/form-data" id="makes">
<span class="btn btn-success fileinput-button">
<span>選擇文件</span>
<input type="file" id="excelFile" name="excelFile">
</span>
<span class="btn btn-success fileinput-button" style="margin: 8% 50%;">
<span onclick="importExc()" >導入</span>
</span>
</form>
</body>
</html>
<script>
function importExc() {
var formData = new FormData();
//檢驗導入的文件是否爲Excel文件
var uploadFile = document.getElementById("excelFile").value;
formData.append("excelFile",$("#excelFile")[0].files[0]);
formData.append("name",uploadFile);
if(uploadFile == null || uploadFile == ''){
layer.msg("請選擇要上傳的Excel文件");
return false;
}else{
var fileExtend = uploadFile.substring(uploadFile.lastIndexOf('.')).toLowerCase();
if(fileExtend == '.xls'){
}else{
layer.msg("文件格式需爲'.xls'格式");
return false;
}
} $.ajax({
type:"post",
url:"${APP_PATH}/importExc",
data:formData,
// 告訴jQuery不要去處理髮送的數據
processData : false,
// 告訴jQuery不要去設置Content-Type請求頭
contentType : false,
beforeSend:function(){
console.log("正在進行,請稍候");
},
success:function (data) {
if(data=="1"){
layer.msg("導入成功");
}else{
layer.error("導入失敗");
}
}
})
}
</script>
Controller層:
@ResponseBody
@RequestMapping("/importExc")
public String importExc(@RequestParam(value="excelFile",required = false) MultipartFile excelFile) {
start();
try {
String s = encryptService.ajaxUploadExcel(excelFile);
return s;
} catch (Exception e) {
e.printStackTrace();
success(false);
}
end();
return "0";
}
Service層:
public interface EncryptService {
String ajaxUploadExcel(MultipartFile excelFile);
}
Service實現層:
@Service("encryptService")
public class EncryptServiceImpl implements EncryptService {
@Autowired
private EncryptDao encryptDao;
public String ajaxUploadExcel(MultipartFile file){
/* MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("excelFile");*/
if(file.isEmpty()){
try {
throw new Exception("文件不存在!");
} catch (Exception e) {
e.printStackTrace();
}
}
InputStream in =null;
try {
in = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
List<List<Object>> listob = null;
try {
listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < listob.size(); i++) {
/* List<Object> lo = listob.get(i);
if (lo.get(i)=="") {
continue;
}*/
System.out.println(listob.get(i));
}
for (int i = 0; i < listob.size(); i++) {
List<Object> lo = listob.get(i);
Encrypt vo = new Encrypt();
Encrypt j = null;
try {
j = encryptDao.selectByPrimaryKey(Integer.valueOf(String.valueOf(lo.get(0))));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
System.out.println("數據庫中無該條數據,新增");
}
vo.setId(Integer.valueOf(String.valueOf(lo.get(0))));
vo.setAppId(String.valueOf(lo.get(1)));
vo.setAppKey(String.valueOf(lo.get(2)));
if(j == null)
{
encryptDao.insert(vo);
System.out.println("susscess");
}
else
{
encryptDao.updateByPrimaryKey(vo);
}
}
return "1";
}
}
Mapper接口:
/**
* 插入數據
* */
int insert(Encrypt encrypt);
/**
* 通過id刪除
* */
int deleteByPrimaryKey(Integer id);
/**
* 插入數據
* */
int insertSelective(Encrypt record);
/**
* 根據id查詢數據
* */
Encrypt selectByPrimaryKey(Integer id);
/**
* 更新數據
* */
int updateByPrimaryKeySelective(Encrypt record);
/**
* 更新數據
* */
int updateByPrimaryKey(Encrypt record);
/**
* 批量插入
* */
void insertInfoBatch(List<Encrypt> list);
Mapper.xml映射:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.cpes.dao.EncryptDao" >
<resultMap id="BaseResultMap" type="com.atguigu.cpes.bean.Encrypt" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="code" property="code" jdbcType="VARCHAR" />
<result column="content" property="content" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, code, content
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from encrypt
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from encrypt
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.atguigu.cpes.bean.Encrypt" >
insert into encrypt (id, code, content)
values (#{id,jdbcType=INTEGER}, #{code,jdbcType=VARCHAR}, #{content,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.atguigu.cpes.bean.Encrypt" >
insert into encrypt
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="code!= null" >
code,
</if>
<if test="content!= null" >
content,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="code!= null" >
#{code,jdbcType=VARCHAR},
</if>
<if test="content!= null" >
#{content,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.atguigu.cpes.bean.Encrypt" >
update encrypt
<set >
<if test="code!= null" >
code= #{code,jdbcType=VARCHAR},
</if>
<if test="content!= null" >
content= #{content,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.atguigu.cpes.bean.Encrypt" >
update encrypt
set username = #{code,jdbcType=VARCHAR},
password = #{content,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
<insert id="insertInfoBatch" parameterType="java.util.List">
insert into encrypt (id, code, content)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{id,jdbcType=INTEGER}, #{code,jdbcType=VARCHAR}, #{content,jdbcType=VARCHAR})
</foreach>
</insert>
</mapper>
上傳工具類:
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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 java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ExcelUtils {
private final static String excel2003L =".xls"; //2003- 版本的excel
private final static String excel2007U =".xlsx"; //2007+ 版本的excel
/**
* 描述:獲取IO流中的數據,組裝成List<List<Object>>對象
* @param in,fileName
* @return
* @throws
*/
public List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception{
List<List<Object>> list = null;
//創建Excel工作薄
Workbook work = this.getWorkbook(in,fileName);
if(null == work){
throw new Exception("創建Excel工作薄爲空!");
}
Sheet sheet = null; //頁數
Row row = null; //行數
Cell cell = null; //列數
list = new ArrayList<List<Object>>();
//遍歷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<Object> li = new ArrayList<Object>();
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 Workbook getWorkbook(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 HSSFWorkbook(inStr); //2007+
}else{
throw new Exception("解析的文件格式有誤!");
}
return wb;
}
/**
* 描述:對錶格中數值進行格式化
* @param cell
* @return
*/
//解決excel類型問題,獲得數值
public String getValue(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<item.length&&"0".equals(item[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;
}
}