excel模板批量导入数据
ssh框架
前端 easyUI封裝后的框架? ?
文件上傳 ajaxfileupload框架
Dto和實(shí)體、Dao方法省略
前端頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="gk" uri="http://***/tags/core"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
</head>
<body>
<script src="/js/ajaxfileupload.js"></script>
<form method="post" enctype="multipart/form-data">
<div style="margin: 50px 50px 15px 180px">
<input id="uploadExcel" type="text" name="uploadExcel"
style="width: 50%">
</div>
<!-- ******? 以下生成頁面按鈕? ****** -->
<button id="save" action="ajaxrequest"
onstart="beforeResourceSave()" value="導(dǎo)入" iconCls="gk-save"
validate="true" />
<script type="text/javascript">
jQuery("#uploadExcel").filebox({
buttonText: '選擇文件',?
? ? buttonAlign: 'left'?
})
function beforeResourceSave(){
var fileName = jQuery("input[name=uploadExcel]")[0].files[0];
var fileid= jQuery("input[name='uploadExcel']").attr("id");
? ? ? ? ? ? ? ? ?//進(jìn)行基本校驗(yàn)??
? ? ? ? ? ? ? ? ?if(fileName==undefined){? ? ?
? ? ? ? ? ? ? ? jQuery.messager.alert('提示','請(qǐng)選擇上傳文件!!','info');? ?
? ? ? ? ? ? ? ? ?}else{??
? ? ? ? ? ? ? ? //對(duì)文件格式進(jìn)行校驗(yàn)??
? ? ? ? ? ? ? ? var index = fileName.name.lastIndexOf(".");
? ? ? ? ? ? ? ? var ext = fileName.name.substring(index + 1,fileName.name.length);
? ? ? ? ? ? ? ? ? //設(shè)置顯示配置
? ? ? ? ? ? ? ? ?var messageOpts = {
? ? ? ? ? ? ? ? ? "closeButton" : true,//是否顯示關(guān)閉按鈕
? ? ? ? ? ? ? ? ? "debug" : false,//是否使用debug模式
? ? ? ? ? ? ? ? ? "positionClass" : "toast-center-center",//彈出窗的位置
? ? ? ? ? ? ? ? ? "onclick" : null,
? ? ? ? ? ? ? ? ? "showDuration" : "300",//顯示的動(dòng)畫時(shí)間
? ? ? ? ? ? ? ? ? "hideDuration" : "1000",//消失的動(dòng)畫時(shí)間
? ? ? ? ? ? ? ? ? "timeOut" : "5000",//展現(xiàn)時(shí)間
? ? ? ? ? ? ? ? ? "extendedTimeOut" : "1000",//加長展示時(shí)間
? ? ? ? ? ? ? ? ? "showEasing" : "swing",//顯示時(shí)的動(dòng)畫緩沖方式
? ? ? ? ? ? ? ? ? "hideEasing" : "linear",//消失時(shí)的動(dòng)畫緩沖方式
? ? ? ? ? ? ? ? ? "showMethod" : "fadeIn",//顯示時(shí)的動(dòng)畫方式
? ? ? ? ? ? ? ? ? "hideMethod" : "fadeOut" //消失時(shí)的動(dòng)畫方式
? ? ? ? ? ? ? ? ? };
? ? ? ? ? ? ? ? ? toastr.options = messageOpts;
? ? ? ? ? ? ? ? ? ? if(ext=="xls"||ext=="xlsx"){?
? ? ? ? ? ? ? ? ? ? jQuery.ajaxFileUpload({??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?url: "/contr/saveExcel.do",? ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?type: 'post',??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?secureuri: false,? ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?fileElementId: fileid,??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?dataType: 'json',? ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?success: function(date){? ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?if(date.success){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? toastr.success("保存成功");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}else{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? toastr.error("保存失敗");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}??
? ? ? ? ? ? ? ? ? ? ? ? ?}); ?
? ? ? ? ? ? ? ? ? ? }else{??
? ? ? ? ? ? ? ? ? ? jQuery.messager.alert('提示','請(qǐng)選擇Excel文件!','info');? ?
? ? ? ? ? ? ? ? ? ? jQuery('#uploadExcel').filebox('setValue','');
? ? ? ? ? ? ? ? ? ? }??
? ? ? ? ? ? ? ? ?}? ??
}
</script>
</form>
</body>
</html>
Controller代碼:
@Controller
@RequestMapping("contr")
public class Controller {?
@Autowired
private??ssService??ssService;
/**
* 導(dǎo)入Excel表格
*? @return
*/
@RequestMapping("saveExcel.do")
@ResponseBody
? ? public String saveExcel(final JsonModel jm,final MultipartHttpServletRequest request,final HttpServletResponse response)? {?
//獲取上傳的文件
MultipartFile multipartFile = request.getFile("uploadExcel");
String filename = multipartFile.getOriginalFilename();
System.out.println(filename);
long size=multipartFile.getSize();
? ? ? ? if(filename==null || ("").equals(filename) && size==0) {?
? ? ? ? throw new AppException("請(qǐng)選擇excel文件");?
? ? ? ? }
? ? ? ? ?//處理Excel讀取數(shù)據(jù)? ? ? ? ?參數(shù):文件名,Excel文件
? ? ? ? List<Dto> dtoList = this.ssService.excelService(filename,multipartFile);?
? ? ? ? ?if(DtoList!=null){
for(Dto dto:dtoList) {
this.ssService.save(dto);
}
? ? ? ? ?}else{
? ? ? ? JsonModel model = new JsonModel();
? ? ? ? model.setSuccess(false);
? ? ? ? model.setErrorMessage("excel數(shù)據(jù)保存失敗");
? ? ? ? return model.toJSON();
? ? ? ? ?}
? ? ? ? ?System.out.println(jm.toJSON());
? ? ? ? ?return jm.toJSON();
}
Service接口:
public interface ssService extends BaseService{
/**
* 讀取導(dǎo)入的excel文件
* @param filename
* @param multipartFile
* @return
*/
List<Dto> excelService(String filename,MultipartFile multipartFile);
/**保存
* @param
*?
*/
void save(Dto? dto);
}
Service實(shí)現(xiàn)類
@Service
public class ssServiceImpl extends BaseServiceImpl implements ssService {
@Autowired
private DtoDao dtoDao;
public void save(Dto? dto){
dtoDao.save(dto);//調(diào)用Dao方法保存
}
public? List<Dto> excelService(String filename,MultipartFile multipartFile){
//創(chuàng)建處理EXCEL
? ? ? ? ReadExcel readExcel=new ReadExcel();
? ? ? ? //解析excel,獲取信息集合? ? ? ??
? ? ? ? List<Dto> dtoList;
try {
dtoList = readExcel.getExcelInfo(filename ,multipartFile);
} catch (Exception e) {
throw new AppException("導(dǎo)入excel失敗");
}
? ? ? ? if(!DtoList.isEmpty()){
? ? ? ? return dtoList;
? ? ? ? }
? ? ? ? return null;
}
}
處理EXCEL類
public class ReadExcel {
//總行數(shù)
? ? private int totalRows = 0;??
? ? //總條數(shù)
? ? private int totalCells = 0;?
? ? //錯(cuò)誤信息接收器
? ? private String errorMsg;
? ? //構(gòu)造方法
? ? public ReadExcel(){}
? ? //獲取總行數(shù)
? ? public int getTotalRows()? { return totalRows;}?
? ? //獲取總列數(shù)
? ? public int getTotalCells() {? return totalCells;}?
? ? //獲取錯(cuò)誤信息
? ? public String getErrorInfo() { return errorMsg; }??
? ??
? /**
? ?* 驗(yàn)證EXCEL文件
? ?* @param filePath
? ?* @return
? ?*/
? public boolean validateExcel(String filePath){
? if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))){??
? ? ? ? ? throw new AppException("文件名不是Excel格式");??
? ? ? }??
? ? ? return true;
? }
? /**
? ?* 讀EXCEL文件,獲取信息集合
? ?* @param fielName
? ?* @return
? ?*/
? public ListDto> getExcelInfo(String fileName,MultipartFile Mfile) throws Exception{
? //把spring文件上傳的MultipartFile轉(zhuǎn)換成CommonsMultipartFile類型
? ? ? CommonsMultipartFile cf= (CommonsMultipartFile)Mfile;?
? ? ??
? ? ? //獲取本地存儲(chǔ)路徑
? ? ? String path="";
? ? ? String path1 = System.getProperties().getProperty("user.dir");//用戶的當(dāng)前工作目錄
? String path2 = System.getProperties().getProperty("java.io.tmpdir");//默認(rèn)的臨時(shí)文件路徑
? if(path2!=null) {
? path = path2;
? }else {
? path = path1;
? }
? System.out.println("path2::::"+path2);
? ? ? File file = new? File(path);
? ? ? //創(chuàng)建一個(gè)目錄 (它的路徑名由當(dāng)前 File 對(duì)象指定,包括任一必須的父路徑。)
? ? ? if (!file.exists()) file.mkdirs();
? ? ? String name1 = path + new Date().getTime() + ".xlsx";
? ? ? System.out.println("name1:::"+name1);
? ? ? //新建一個(gè)文件
? ? ? File file1 = new File(name1);?
? ? ? //將上傳的文件寫入新建的文件中
? ? ? try {
? ? ? ? ? cf.getFileItem().write(file1);?
? ? ? } catch (Exception e) {
? ? ? ? ? e.printStackTrace();
? ? ? }
? ? ? //初始化信息的集合? ??
? ? ? List<Dto> dtoList=new ArrayList<Dto>();
? ? ? //初始化輸入流
? ? ? InputStream is = null;??
? ? ? try{
? ? ? ? ?//驗(yàn)證文件名是否合格
? ? ? ? ?if(!validateExcel(fileName)){
? ? ? ? ? ? ?return null;
? ? ? ? ?}
? ? ? ? ?//根據(jù)文件名判斷文件是2003版本還是2007版本
? ? ? ? ?boolean isExcel2003 = true;?
? ? ? ? ?if(isExcel2007(fileName)){
? ? ? ? ? ? ?isExcel2003 = false;??
? ? ? ? ?}
? ? ? ? ?//根據(jù)新建的文件實(shí)例化輸入流
? ? ? ? ?is = new FileInputStream(file1);
? ? ? ? ?//根據(jù)excel里面的內(nèi)容讀取信息
? ? ? ? ?dtoList = getExcelInfo(is, isExcel2003);?
? ? ? ? ?is.close();
? ? ? ? ?
? ? ? ? ?// 如果文件路徑所對(duì)應(yīng)的文件存在,并且是一個(gè)文件,則直接刪除
? ? ? ? ?if (file1.exists() && file1.isFile()) {
? ? ? ? ? ? ?if (file1.delete()) {
? ? ? ? ? ? ? ? ?System.out.println("刪除單個(gè)文件" + name1 + "成功!");
? ? ? ? ? ? ?} else {
? ? ? ? ? ? ? ? ?System.out.println("刪除單個(gè)文件" + name1 + "失敗!");
? ? ? ? ? ? ?}
? ? ? ? ?} else {
? ? ? ? ? ? ?System.out.println("刪除單個(gè)文件失敗:" + name1 + "不存在!");
? ? ? ? ?}
? ? ?}catch(Exception e){
? ? ? ? ?e.printStackTrace();
? ? ?} finally{
? ? ? ? ?if(is !=null)
? ? ? ? ?{
? ? ? ? ? ? ?try{
? ? ? ? ? ? ? ? ?is.close();
? ? ? ? ? ? ?}catch(IOException e){
? ? ? ? ? ? ? ? ?is = null;? ??
? ? ? ? ? ? ? ? ?e.printStackTrace();??
? ? ? ? ? ? ?}
? ? ? ? ?}
? ? ?}?
??
? return D104DtoList;
? }
? /**
? ?* 根據(jù)excel里面的內(nèi)容讀取客戶信息
? ?* @param is 輸入流
? ?* @param isExcel2003 excel是2003還是2007版本
? ?* @return
? ?* @throws IOException
? ?*/
? public? List<Dto> getExcelInfo(InputStream is,boolean isExcel2003){
? ? ? ?List<Dto> dtoList=null;
? ? ? ?try{
? ? ? ? ? ?/** 根據(jù)版本選擇創(chuàng)建Workbook的方式 */
? ? ? ? ? ?Workbook wb = null;
? ? ? ? ? ?//當(dāng)excel是2003時(shí)
? ? ? ? ? ?if(isExcel2003){
? ? ? ? ? ? ? ?wb = new HSSFWorkbook(is);?
? ? ? ? ? ?}
? ? ? ? ? ?else{//當(dāng)excel是2007時(shí)
? ? ? ? ? ? ? ?wb = new XSSFWorkbook(is);?
? ? ? ? ? ?}
? ? ? ? ? ?//讀取Excel里面客戶的信息
? ? ? ? ? ?dtoList=readExcelValue(wb);
? ? ? ?}
? ? ? ?catch (IOException e)? {??
? ? ? ? ? ?e.printStackTrace();??
? ? ? ?}??
? ? ? ?return dtoList;
? }? ?
? /**
? ?* 讀取Excel里面客戶的信息
? ?* @param wb
? ?* @return
? ?*/
? private List<Dto> readExcelValue(Workbook wb){?
? ? ? //得到第一個(gè)shell??
? ? ? ?Sheet sheet=wb.getSheetAt(0);
? ? ? ?
? ? ? //得到Excel的行數(shù)
? ? ? ?this.totalRows=sheet.getPhysicalNumberOfRows();
? ? ? ?
? ? ? //得到Excel的列數(shù)(前提是有行數(shù))
? ? ? ?if(totalRows>=1 && sheet.getRow(0) != null){
? ? ? ? ? ? this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells();
? ? ? ?}
? ? ? ?
? ? ? ?List<Dto> dtoList=new ArrayList<Dto>();
? ? ? ?Dto dto;? ? ? ? ? ??
? ? ? //循環(huán)Excel行數(shù),從第二行開始 標(biāo)題不入庫
? ? ? ?for(int r=1;r<totalRows;r++){
? ? ? ? ? ?Row row = sheet.getRow(r);
? ? ? ? ? ?if (row == null)?
? ? ? ? ? ?continue;
? ? ? ? ?dto = new Dto();
? ? ? ? ? ?//循環(huán)Excel的列
? ? ? ? ? ?for(int c = 0; c <this.totalCells; c++){? ??
? ? ? ? ? ? ? ?Cell cell = row.getCell(c);
? ? ? ? ? ? ? ?if (null != cell){
? ? ? ? ? ? ? ? ? ?if(c==0){//讀取格子
? ? ? ? ? ? ? ? ? ?dto.setDto01(cell.getStringCellValue());//名稱
? ? ? ? ? ? ? ? ? ?}else if(c==1){
? ? ? ? ? ? ? ? ? ?dto.setDto02(cell.getStringCellValue());//簡稱
? ? ? ? ? ? ? ? ? ?}else if(c==2){
? ? ? ? ? ? ? ? ? ?if(cell!=null) {
? ? ? ? ? ? ? ? ? ?cell.setCellType(Cell.CELL_TYPE_STRING);? ?//Excel 中 number類型數(shù)據(jù)要先轉(zhuǎn)為String類型在讀取
? ? ? ? ? ? ? ? ? ?dto.setDto03(cell.getStringCellValue());//編號(hào)
? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ?}else if(c==3){
? ? ? ? ? ? ? ? ? ?dto.setDto04(cell.getStringCellValue());//地址
? ? ? ? ? ? ? ? ? ?}else if(c==4){
? ? ? ? ? ? ? ? ? ?dto.setDto05(cell.getStringCellValue());//負(fù)責(zé)人
? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ?}
? ? ? ? ? ?}
? ? ? ? ? ? //添加
? ? ? ? ? ? dtoList.add(dto);
? ? ? ?}
? ? ? ?return dtoList;
? }
??
??
??
??
??
??
? // @描述:是否是2003的excel,返回true是2003?
? public static boolean isExcel2003(String filePath)? {??
? ? ? ?return filePath.matches("^.+\\.(?i)(xls)$");??
? ?}??
?
? //@描述:是否是2007的excel,返回true是2007?
? public static boolean isExcel2007(String filePath)? {??
? ? ? ?return filePath.matches("^.+\\.(?i)(xlsx)$");??
? ?}?
總結(jié)
以上是生活随笔為你收集整理的excel模板批量导入数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android数据编码之Base64
- 下一篇: 传说中的b站mac客户端(支持M1芯片、