在springmvc項目中使用poi導入導出excel
來源:程序員人生 發布時間:2014-09-26 19:44:12 閱讀次數:3146次
首先要導入spring相關包,poi,和fileupload包,我是使用maven構建的。
一.導入excel
(1)使用spring上傳文件
a.前臺頁面提交
<form name="excelImportForm" action="${pageContext.request.contextPath}/brand/importBrandSort" method="post" onsubmit="return checkImportPath();" enctype="multipart/form-data" id="excelImportForm">
<input type="hidden" name="ids" id="ids">
<div class="modal-body">
<div class="row gap">
<label class="col-sm-7 control-label"><input class="btn btn-default" id="excel_file" type="file" name="filename" accept="xls"/></label>
<div class="col-sm-3">
<input class="btn btn-primary" id="excel_button" type="submit" value="導入Excel"/>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onClick="uncheckBoxes();">取消</button>
</div>
在提交前可進行一些判斷,可查看:
http://blog.csdn.net/kingson_wu/article/details/38928827
b.后臺spring的controller進行相關操作,這里主要講的是使用spring上傳文件,和讀取文件信息,可以參考這兩篇文章:
http://endual.iteye.com/blog/1810170
http://dakulaliu.iteye.com/blog/236235
使用spring上傳文件之前,需要配置bean
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
@RequestMapping(value = "/importBrandSort", method = RequestMethod.POST)
public ModelAndView importBrandSort(@RequestParam("filename") MultipartFile file,
HttpServletRequest request,HttpServletResponse response) throws Exception {
String temp = request.getSession().getServletContext()
.getRealPath(File.separator)
+ "temp"; // 臨時目錄
File tempFile = new File(temp);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
DiskFileUpload fu = new DiskFileUpload();
fu.setSizeMax(10 * 1024 * 1024); // 設置允許用戶上傳文件大小,單位:位
fu.setSizeThreshold(4096); // 設置最多只允許在內存中存儲的數據,單位:位
fu.setRepositoryPath(temp); // 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬盤的目錄
// 開始讀取上傳信息
// int index = 0;
/* List fileItems = null;
try {
fileItems = fu.parseRequest(request);
} catch (Exception e) {
e.printStackTrace();
}
Iterator iter = fileItems.iterator(); // 依次處理每個上傳的文件
FileItem fileItem = null;
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表單信息
if (!item.isFormField()) {
fileItem = item;
// index++;
}
}
if (fileItem == null)
return null;
*/
if (file == null)
return null;
logger.info(file.getOriginalFilename());
String name = file.getOriginalFilename();// 獲取上傳文件名,包括路徑
//name = name.substring(name.lastIndexOf("") + 1);// 從全路徑中提取文件名
long size = file.getSize();
if ((name == null || name.equals("")) && size == 0)
return null;
InputStream in = file.getInputStream();
List<BrandMobileInfoEntity> BrandMobileInfos = brandService
.importBrandPeriodSort(in);
// 改為人工刷新緩存KeyContextManager.clearPeriodCacheData(new
// PeriodDimensions());// 清理所有緩存
int count = BrandMobileInfos.size();
String strAlertMsg ="";
if(count!=0){
strAlertMsg= "成功導入" + count + "條!";
}else {
strAlertMsg = "導入失敗!";
}
logger.info(strAlertMsg);
//request.setAttribute("brandPeriodSortList", BrandMobileInfos);
//request.setAttribute("strAlertMsg", strAlertMsg);
request.getSession().setAttribute("msg",strAlertMsg);
return get(request, response);
//return null;
}
代碼中的注釋部分是如果不使用spring的方式,如何拿到提交過來的文件名(需要是要apache的一些工具包),其實使用spring的也是一樣,只是已經做好了封裝,方便我們寫代碼。
代碼中的后半部分是讀取完上傳文文件的信息和對數據庫進行更新之后,輸出到前臺頁面的信息。
這里給頁面設置session信息,前臺檢測session提示是否導入成功。具體可參考:
http://blog.csdn.net/kingson_wu/article/details/38926771
上述代碼中:
InputStream in = file.getInputStream();
List<BrandMobileInfoEntity> BrandMobileInfos = brandService
.importBrandPeriodSort(in);
讀取excel的信息。
(2)使用poi讀取excel
a.更新數據庫
@Override
public List<BrandMobileInfoEntity> importBrandPeriodSort(InputStream in) throws Exception {
List<BrandMobileInfoEntity> brandMobileInfos = readBrandPeriodSorXls(in);
for (BrandMobileInfoEntity brandMobileInfo : brandMobileInfos) {
mapper.updateByConditions(brandMobileInfo);
}
return brandMobileInfos;
}
這部分是sevice層的代碼,用于讀取excel信息之后更新數據庫數據,我這里是使用mybatis。定義一個類BrandMobileInfoEntity,用與保存excel表每一行的信息,而List<
BrandMobileInfoEntity>則保存了全部信息,利用這些信息對數據庫進行更新。
b.讀取excel信息
private List<BrandMobileInfoEntity> readBrandPeriodSorXls(InputStream is)
throws IOException, ParseException {
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
List<BrandMobileInfoEntity> brandMobileInfos = new ArrayList<BrandMobileInfoEntity>();
BrandMobileInfoEntity brandMobileInfo;
// 循環工作表Sheet
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 循環行Row
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
brandMobileInfo = new BrandMobileInfoEntity();
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
for (int i = 0; i < hssfRow.getLastCellNum(); i++) {
HSSFCell brandIdHSSFCell = hssfRow.getCell(i);
if (i == 0) {
brandMobileInfo.setBrandId(Integer
.parseInt(getCellValue(brandIdHSSFCell)));
} else if (i == 1) {
continue;
} else if (i == 2) {
brandMobileInfo.setMobileShowFrom(Integer.parseInt(getCellValue(brandIdHSSFCell)));
} else if (i == 3) {
brandMobileInfo.setMobileShowTo(Integer.parseInt(getCellValue(brandIdHSSFCell)));
} else if (i == 4) {
brandMobileInfo.setSellMarkValue(getCellValue(brandIdHSSFCell));
} else if (i == 5) {
brandMobileInfo.setWarehouse(getCellValue(brandIdHSSFCell));
} else if (i == 6) {
brandMobileInfo.setSortA1(Integer.parseInt(getCellValue(brandIdHSSFCell)));
} else if (i == 7) {
brandMobileInfo.setSortA2(Integer.parseInt(getCellValue(brandIdHSSFCell)));
} else if (i == 8) {
brandMobileInfo.setSortB(Integer.parseInt(getCellValue(brandIdHSSFCell)));
} else if (i == 9) {
brandMobileInfo.setSortC10(Integer.parseInt(getCellValue(brandIdHSSFCell)));
} else if (i == 10) {
brandMobileInfo.setSortC(Integer.parseInt(getCellValue(brandIdHSSFCell)));
} else if (i == 11) {
brandMobileInfo.setHitA(getCellValue(brandIdHSSFCell));
} else if (i == 12) {
brandMobileInfo.setHitB(getCellValue(brandIdHSSFCell));
} else if (i == 13) {
brandMobileInfo.setHitC(getCellValue(brandIdHSSFCell));
} else if (i == 14) {
brandMobileInfo.setCustomSellType(getCellValue(brandIdHSSFCell));
}else if (i == 15) {
continue;
}else if (i == 16) {
brandMobileInfo.setChannelId(Integer.parseInt(getCellValue(brandIdHSSFCell)));
}
}
brandMobileInfos.add(brandMobileInfo);
}
}
return brandMobileInfos;
}
這種代碼有點搓,還沒有優化,可以大概看到是怎么讀取信息的。
(3)使用mybatis更新數據
二.導出excel
(1)
前臺頁面使用一個按鈕,定義js事件:
$(".exportBrandSort").on('click', function() {
var url = contextPath+"/brand/exportBrandSort";
$('#searchform').attr('action', url);
$('#searchform').submit();
//還原action值
url = contextPath+"/brand/getBrand";
$('#searchform').attr('action', url);}
這里使用查詢功能的form的表單,則導出的就是查詢之后的信息的excel表格。
可參考:
http://blog.csdn.net/kingson_wu/article/details/38927915
(2)后臺controller處理
a.后端controller處理并輸出到前臺
@RequestMapping(value = "/exportBrandSort", method = RequestMethod.GET)
public void exportBrandSort(HttpServletRequest request,
HttpServletResponse response) throws Exception {
try {
Map<String, Object> params = new HashMap<>();
// start time of selling
String startTimeStr = RequestUtil.getStringParameter(request,
"startTimeStr", null);
if (StringUtils.isNotBlank(startTimeStr)) {
params.put("startTimeStr", startTimeStr);
params.put("startTime", df.parse(startTimeStr).getTime() / 1000);
}
// end time of selling
String endTimeStr = RequestUtil.getStringParameter(request,
"endTimeStr", null);
if (StringUtils.isNotBlank(endTimeStr)) {
params.put("endTimeStr", endTimeStr);
params.put("endTime", df.parse(endTimeStr).getTime() / 1000);
}
// warehouse
String warehouse = RequestUtil.getStringParameter(request,
"warehouse");
if (StringUtils.isNotBlank(warehouse)) {
params.put("warehouse", warehouse);
}
// channel
String channel4ui = BrandConstants.CHANNEL_ID_SEARCH_DEFAULT;
String[] channel = request.getParameterValues("channel");
if (channel != null && channel.length > 0) {
channel4ui = stringArrayToString(channel);
}
params.put("channel", channel4ui);
String orderType = request.getParameter("orderType");
if (orderType == null || "".equals(orderType)) {
orderType = "C";
}
params.put("orderType", orderType);
// brand id
if (RequestUtil.getIntParameter(request, "brandId") > 0)
params.put("brandId",
(RequestUtil.getIntParameter(request, "brandId")));
// brand name
if (RequestUtil.getStringParameter(request, "brandName") != null
&& !"".equals(RequestUtil.getStringParameter(request,
"brandName").trim()))
// params.put("brandName", new
// String(RequestUtil.getStringParameter(request,
// "brandName").getBytes("ISO-8859-1"),"UTF-8"));
params.put("brandName",
RequestUtil.getStringParameter(request, "brandName"));
int count = brandService.countByConditions(params);
List<BrandCompleteInfoEntity> list = brandService
.queryBrands(params);
// --------
byte[] fileNameByte = ("kxw.xls").getBytes("GBK");
String filename = new String(fileNameByte, "ISO8859-1");
byte[] bytes = brandService.exportBrandPeriodSort(list);
// logger.info("------------------------"+bytes.length);
response.setContentType("application/x-msdownload");
//response.setContentType("application/x-excel");
response.setContentLength(bytes.length);
response.setHeader("Content-Disposition", "attachment;filename="
+ filename);
response.getOutputStream().write(bytes);
//response.getOutputStream().flush();
} catch (Exception ex) {
logger.debug(ex.getMessage());
}
}
代碼中前半部分只是根據表單信息去后臺那數據并保存在List<BrandCompleteInfoEntity>中,可忽略細節。
關鍵是把List<BrandCompleteInfoEntity>拼接成excel并輸出到網頁中。
這里注意該方法的返回值是void,否則如果是ModelAndView或者String等類型,提交之后會發生跳轉,返回null則是跳轉到空白頁面。
代碼中:
byte[] fileNameByte = ("檔期列表.xls").getBytes("GBK");
String filename = new String(fileNameByte, "ISO8859-1");
byte[] bytes = brandService.exportBrandPeriodSort(list);
是拼接excel。
b.拼接excel(service層)
@Override
public byte[] exportBrandPeriodSort(List<BrandCompleteInfoEntity> list) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 第一步,創建一個webbook,對應一個Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("檔期排序表");
// 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制short
HSSFRow row = sheet.createRow((int) 0);
// 第四步,創建單元格,并設置值表頭 設置表頭居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創建一個居中格式
//設置表頭
List<String> excelHead = getExcelHead();
HSSFCell cell = null;
// excel頭
for (int i = 0; i < excelHead.size(); i++) {
cell = row.createCell(i);
cell.setCellValue(excelHead.get(i));
cell.setCellStyle(style);
}
// 第五步,寫入實體數據 實際應用中這些數據從數據庫得到
//List<BrandPeriodSortEntity> list = getBrandPeriodSortDynamicOrder(entity, orderType);
BrandCompleteInfoEntity brandCompleteInfo = null; // 拼裝excel內容
for (int i = 0; i < list.size(); i++) {
row = sheet.createRow((int) i + 1);
brandCompleteInfo = list.get(i);
// 創建單元格,并設置值
int j=0;
insertCell(row, j++, brandCompleteInfo.getBrandId());
insertCell(row, j++, brandCompleteInfo.getBrandName());
insertCell(row, j++, brandCompleteInfo.getMobileShowFrom());
insertCell(row, j++, brandCompleteInfo.getMobileShowTo());
insertCell(row, j++, brandCompleteInfo.getSellMarkValue());
insertCell(row, j++, brandCompleteInfo.getWarehouse());
insertCell(row, j++, brandCompleteInfo.getSortA1());
insertCell(row, j++, brandCompleteInfo.getSortA2());
insertCell(row, j++, brandCompleteInfo.getSortB());
insertCell(row, j++, brandCompleteInfo.getSortC10());
insertCell(row, j++, brandCompleteInfo.getSortC());
insertCell(row, j++, brandCompleteInfo.getHitA());
insertCell(row, j++, brandCompleteInfo.getHitB());
insertCell(row, j++, brandCompleteInfo.getHitC());
insertCell(row, j++, brandCompleteInfo.getCustomSellType());
insertCell(row, j++, channelInfoMapper.loadChannelNameById(brandCompleteInfo.getChannelId()));
insertCell(row, j++, brandCompleteInfo.getChannelId());
}
wb.write(out);
return out.toByteArray();
}
/**
* 獲取excel表頭
*
* @return
*/
private List<String> getExcelHead() {
List<String> result = new ArrayList<String>(17);
result.add("XXXXX");
result.add("XXXXX");
result.add("XXXXX");
result.add("XXXXX");
result.add("XXXXX");
result.add("XXXXX");
result.add("XXXXX");
result.add("XXXXX");
result.add("XXXXX");
result.add("XXXXX");
//。。。。
return result;
}
private void insertCell(HSSFRow row,int i,Object object){
if(object==null){
row.createCell(i).setCellValue("");
}else{
row.createCell(i).setCellValue(object.toString());
}
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈