springmvc Excel檔案上傳,使用ajaxSubmit方法進行檔案上傳,使用彈出層彈出一個框(jquery layer),點選進行下載
效果:
彈出層使用的是jquery外掛layer 外掛下載地址http://download.csdn.net/detail/rendeyishi/8048139
因為我是使用的是jquery裡面的ajaxSubmit進行檔案上傳 所以這個jquery.form.js必須存在
還需要的js檔案是:layer.min.js jquery-1.7.2.js
例子script程式碼:
<a href="javascript:void(0);" id="import" class="easyui-linkbutton" >Excel匯入</a>
$('#import').on('click', function(){
var pageii = $.layer({
type: 1,
title: false,
area: ['auto', 'auto'],
border: [0], //去掉預設邊框
closeBtn: [0, false], //去掉預設關閉按鈕
shift: 'left', //從左動畫彈出
page: {
html: '<div style="width:420px; height:260px; padding:20px; border:1px solid #ccc; background-color:#eee;">'+
'<button type="button" id="download">下載Excel模板</button><button id="pagebtn" class="btns" onclick="">關閉</button>'+
'<form id="upload" enctype="multipart/form-data" action="${basePath}/payment/importBuildInfoExcel.html" method="post">'+
' <input name="fileBuildInfo" id="fileBuildInfo" class="big" type="file" />
'<input type="button" id="importBuildInfo"class="btns" value="匯入"/>'+
' </form>'+
'</div>'
}
});
//自設關閉
$('#pagebtn').on('click', function(){
layer.close(pageii);
});
//點選匯入的時候觸發的事件
$('#importBuildInfo').on('click',function(){
if($('#fileBuildInfo').val()==""){
alert("請先選擇要上傳的房屋資訊檔案!");
}else{
$('#upload').ajaxSubmit({
url:"${basePath}/payment/importBuildInfoExcel.html",
cache:false,
dataType:'json',
success: function(data) {
if(data.result!=null){
$.each(data.result,function(i,value){
alert(value);
});
}
} ,
error:function(){
alert("error");
}
});
}
});
//下載excel模板
$('#download').on('click',function(){
location.href="${basePath}/payment/downloadInfo.html";
});
});
下載模板的方法
/**
* 下載房屋資訊模板
* @author ljr
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/downloadInfo")
@ResponseBody
public void download(HttpServletRequest request,HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=UTF-8");
BufferedInputStream in = null;
BufferedOutputStream out = null;
request.setCharacterEncoding("UTF-8");
String separator = File.separator;
String rootpath = request.getSession().getServletContext().getRealPath(separator+"upload");
String fileName = "ImportTemplate.xlsx";
try {
File f = new File(rootpath + separator + fileName);
response.setContentType("application/x-excel");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
response.setHeader("Content-Length",String.valueOf(f.length()));
in = new BufferedInputStream(new FileInputStream(f));
out = new BufferedOutputStream(response.getOutputStream());
byte[] data = new byte[1024];
int len = 0;
while (-1 != (len=in.read(data, 0, data.length))) {
out.write(data, 0, len);
}
} catch (Exception e) {
logger.error("下載房屋資訊模版異常:",e);
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
因為我檔案上傳我使用的springmvc:
所以配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="20000000"/>
</bean>
檔案上傳程式碼:
@RequestMapping("/importBuildInfoExcel")
@ResponseBody
public DefaultResult importBuildInfoExcel(@RequestParam(value="fileBuildInfo",required=false) MultipartFile buildInfo,HttpServletRequest request,HttpServletResponse response){
try {
if (buildInfo != null) {
String path = request.getSession().getServletContext().getRealPath("/upload")+"/"+buildInfo.getOriginalFilename();
File file=ToolKit.getFileFromBytes(buildInfo.getBytes(), path);//需要先儲存在本地
List<BuildInfo> list=BuildInfoExcel.importBuildInfo(file, request);//這裡是解析excel檔案
DefaultResult dr=buildInfoService.insertBuildInfoCommunity(list, logger);//這裡做的是一個插入資料庫功能
if(dr.getResult()!=null){
List<String> returnList=(List<String>) dr.getResult();
for (String s : returnList) {
logger.info(s);
}
}
ToolKit.deleteFile(path);
return dr;
}
} catch (IOException e) {
logger.error("匯入房屋資訊報錯:",e);
}
return null;
}
解析excel的程式碼
public static List<BuildInfo> importBuildInfo(File file ,HttpServletRequest request){
try {
// 建立需要批量插入資料集合
List<BuildInfo> list = new ArrayList<BuildInfo>();
// 建立一個FileInputStream 檔案輸入流
FileInputStream inputStream = new FileInputStream(file);
// 建立對Excel工作簿檔案的引用
Workbook wookbook = null;
String name = file.getName();
String fileType = name.substring(name.lastIndexOf(".") + 1,
name.length());
if (fileType.equals("xlsx")) {
wookbook = new XSSFWorkbook(inputStream);
} else if (fileType.equals("xls")) {
wookbook = new HSSFWorkbook(inputStream);
}
// 在Excel文件中,第一張工作表的預設索引是0
Sheet sheet = wookbook.getSheetAt(0);
// 獲取到Excel檔案中的所有行數
int rows = sheet.getPhysicalNumberOfRows();
// 遍歷行 從第二行開始遍歷
for (int i = 1; i < rows; i++) {
// 讀取左上端單元格
Row row = sheet.getRow(i);
// 行不為空
if (row != null) {
// 建立物件
BuildInfo object = new BuildInfo();
object.setRow(i+1);
object.setCommunityName((row.getCell(0)
.getStringCellValue()).trim());// 獲取小區名稱
object.setHomeAddress((row.getCell(1).getStringCellValue())
.trim());// 獲取房屋資訊
// 設定姓名
Cell nameCell = row.getCell(2);
if (nameCell != null && !nameCell.equals("")) {
nameCell.setCellType(Cell.CELL_TYPE_STRING);
String bname = nameCell.getStringCellValue().trim();
if (bname != null && StringUtils.isEmpty(bname)) {
object.setName(bname);
}
}
// 設定性別
Cell sexCell = row.getCell(3);
if (sexCell != null && !sexCell.equals("")) {
sexCell.setCellType(Cell.CELL_TYPE_STRING);
String sex = sexCell.getStringCellValue().trim();
if(sex.equals("男")|| sex.equals("女")){
object.setSex(sex);
}
}
Cell homeAreaCell = row.getCell(4);
if (homeAreaCell != null && !homeAreaCell.equals("")) {
homeAreaCell.setCellType(Cell.CELL_TYPE_STRING);
String homeAreaString = homeAreaCell
.getStringCellValue().trim();
if (!homeAreaString.equals("")) {
try {
Float homeArea = Float
.parseFloat(homeAreaString);
object.setHomeArea(homeArea);
} catch (NumberFormatException e) {
object.setHomeArea(null);
}
}
}
Cell mobileCell = row.getCell(5);
if (mobileCell != null && !(mobileCell.equals(""))) {
mobileCell.setCellType(Cell.CELL_TYPE_STRING);
String mobile = mobileCell.getStringCellValue().trim();
if (!mobile.equals("")) {
object.setPhone(mobile);
}
}
// 將物件增加到集合中
list.add(object);
}
}
// 返回集合
return list;
} catch (IOException e) {
logger.error("建立匯入excel物件報錯!", e);
}
return null;
}
//根據byte[]獲取file
/**
* 根據位元組陣列獲取File
* @param b 位元組陣列
* @param outputFile 輸出的路徑(儲存路徑)
* @return
*/
public static File getFileFromBytes(byte[] b, String outputFile) {
BufferedOutputStream stream = null;
File file = null;
try {
file = new File(outputFile);
FileOutputStream fstream = new FileOutputStream(file);
stream = new BufferedOutputStream(fstream);
stream.write(b);
} catch (Exception e) {
logger.error("檔案儲存出錯",e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e1) {
logger.error("檔案流關閉出錯",e1);
}
}
}
return file;
}
相關推薦
springmvc Excel檔案上傳,使用ajaxSubmit方法進行檔案上傳,使用彈出層彈出一個框(jquery layer),點選進行下載
效果: 彈出層使用的是jquery外掛layer 外掛下載地址http://download.csdn.net/detail/rendeyishi/8048139 因為我是使用的是jquery裡面的ajaxSubmit進行檔案上傳 所以這個jquery.form.js必
MFC中點選文字框顯示提示,點選其他地方提示消失的方法
BOOL CPrjDlg::PreTranslateMessage(MSG* pMsg) {if ((pMsg->message == WM_LBUTTONDOWN) || (pMsg->message == WM_LBUTTONUP)) //核心點
基於jQuery和cropper點選頭像上傳並預覽裁剪圖片
使用jquery上傳前,預覽圖片,裁剪,示例使用php接收上傳的檔案,並且儲存為裁剪後的圖片。不需要上傳後再裁剪圖片,只需要本地裁剪好即可,裁剪的時候也可以旋轉圖片。裁剪控制元件使用了,cropper。 html程式碼 <!DOCTYPE html> <html la
POI匯出Excel檔案,瀏覽器點選可下載
說明:使用SpringMVC+POI 1:服務端程式碼 /** * 匯出日誌查詢列表 */ @RequestMapping(value = "/log_excel") public void exportLogList(HttpS
js 移動端漂亮input框上傳本地,顯示縮圖,點選可以檢視大圖
//首先根據id得到input框的檔案,判斷大小,如果大於100M就不給上傳,如果不大於就可以上傳 $("input[type='file']").on("change",function(){ var load =$(this).attr("id"); var fileSize
硬碟分割槽檔案格式變成RAW,點選就顯示未格式化解決方法(小莫)
硬碟分割槽檔案格式變成RAW,點選就顯示未格式化。但格式化又失敗解決方法 以上問題都是分割槽由於某種原因造成了格式變化成RAW了,具體原因可能有很多,下面有幾種方法解決的方法也有幾個,西部e網歸納了一下,遇到此問題的朋友根據情況來解決吧!方案1、2只對原系統是NTFS格式有效
記錄Android開發一個小坑,佈局檔案TextView中新增onClick後,點選無效問題
自己寫東西的時候,在TextView上添加了onClick去增加點選事件,去跳轉另一個Activity,執行後結果點選無效,新增Toast,Toast也不顯示,程式碼如下: <TextView android:layout_width="wrap_content"
GridView 使用,GirdView 方法屬性。GirdView 長按出現右上角圖示,點選圖示刪除
介面卡和 ListView 一樣。 GirdView 方法屬性 <GridView android:id="@+id/gv" android:horizontalSpacing="5dp" android:n
js實現點選按鈕下載檔案並儲存
首先,感謝https://www.cnblogs.com/hamsterPP/p/6763458.html分享。 1、初衷:最近做黑盒性功能測試,被測試系統在本人的電腦上無法通過chrome、IE瀏覽器下載檔案,而開發人員卻說他的瀏覽器可以。 2、自己試著去了解下載功能的實現: (1)從
Android短視訊開發中通過點選進行的命令操作所需原始碼合集
在短視訊操作中,“點選識別命令”的操作是非常常見的,幾乎一切命令都需要靠使用者點選來實現,因此,在Android短視訊開發中,雙擊點贊,點選評論、關注、分享,點選頭像進入主頁功能都是最常見的功能。 接下來,我將從程式碼的角度為大家展現這些功能的實現方式: 【雙擊點贊】通過此
selenium使用Xpath+CSS+JavaScript+jQuery的定位方法(治療selenium各種定位不到,點選不了的併發症)
轉載地址:https://blog.csdn.net/cyjs1988/article/details/76284289 【第一部分】開篇:先認識Xpath的4種定位方法 跟你說,你總是靠那個firebug,chrome的F12啥的右擊複製xpath絕對總有一天踩著地雷炸的你死活定位不到,這
web端 - 返回上一步,點選返回,跳轉上個頁面 JS
1.方法一: <script language="javascript" type="text/javascript"> window.location.href="login.jsp?backurl="+window.location.href; </script>
VS程式設計,編輯WPF過程中,點選設計器中介面某一控制元件,在XAML中高亮突出顯示相應的控制元件程式碼的設定方法。
在編輯製件WPF過程中,當介面中控制元件較多時,可通過點選設計器中具體的控制元件,從而中在xaml程式碼視窗中快速跳轉到對應的部分。為了突出顯示該部分控制元件程式碼的名稱,方便視覺上直觀的觀察到被選中的控制元件對應的XAML程式碼,可以在VS中設定:選中控制元件後,高亮顯示對應的XAML
js點選按鈕下載圖片、word、pdf、excel等
html: <button class="download" onclick=" download('url')"> <i class="layui-icon layui-icon-download-circle"><
React-Native上拉重新整理下拉載入,點選跳轉詳情程式碼解析
React-Native 上拉重新整理下拉載入,點選跳轉詳情程式碼解析 配置路由器 import { createTabNavigator, createStackNavigator } from "react-navigation"; import New1
vue元件通訊,點選傳值,動態傳值(父傳子,子傳父)
vue說到元件通訊,無非是父元件傳子元件,子元件傳父元件,跨級元件傳值,同級元件傳值,個人覺得,除了父子元件的傳值,其餘情況就可以用vuex來解決了,這篇先不說vuex,這裡介紹父子元件傳值。不會你打我! 一、父元件傳子元件,核心--props 下面是場景,點選傳值給子元
jq 鍵盤事件,點選鍵盤上的上鍵,input上一個獲取焦點,點選下鍵,input下一個獲取焦點
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script
NSTextField 處於編輯狀態時,點選return鍵 結束編輯,NSButton的return快捷方法不響應
NSButton 設定快捷鍵 return, 當 NSTextField 處於編輯狀態時, 點選return鍵 結束編輯,要求不響應button的return快捷方法 attributes inspector 面板中設定 NSTextField 的 Action 屬性 為 Send On Ent
一個可以隨手勢拖動的EditText,點選更改內容,附帶解決軟鍵盤遮擋終極方法
慣例先來看效果圖: 最近產品同學的需求,要求定製一個可拖拽可編輯的文字,原本覺得還挺簡單,不就是寫個EditText處理一下touch事件麼,後來做了發現還有些小坑,記錄一下,順便給大家做個參考。 試錯 首先我嘗試自定義一個EditText,重寫o
點選事件,選擇按鈕,點選從前端傳到後臺,查詢資料,並返回前段,顯示出來。---tp5
//這是HTML頁面 <div class="form-group"> <label class="col-sm-3">聽讀寫說分類</label>