報表格式Excel的匯入,匯出
一,匯入
1,前臺頁面用type="file"接受要匯入的檔案,
例如:<input style="display: inline-block;max-width: 170px;border: 2px solid #e6e6e6;" id="uploadFile" name="uploadFile"type="file"accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>;
傳入後臺用: fileElementId:$('input[name=uploadFile]')
例如:$("#doLeadingInGoods").click(function () {
var val= $("#uploadFile").val();
var k = val.substr(val.indexOf("."));
if(k=='.xlsx'||k=='.xls'||k=='.XLSX'||k=='.XLS'){
ajaxLoading();
$.ajaxFileUpload({
url:"${base}/weipu/mallgoods/saveGoods",
secureuri:true,//是否啟用安全提交,預設為false
fileElementId:$('input[name=uploadFile]')
dataType:'text',
async:true,
success:function(data, status){//伺服器響應成功時的處理函式
data = data.replace(/<pre.*?>/g, '');
data = data.replace(/<PRE.*?>/g, '');
data = data.replace("<PRE>", '');
data = data.replace("</PRE>", '');
data = data.replace("<pre>", '');
data = data.replace("</pre>", '');
data = jQuery.parseJSON(data);
if(data.status=='success'){
}else{
ajaxLoadEnd();
layer.alert(data.message);
}
},
error:function(data, status, e){ //伺服器響應失敗時的處理函式
data = data.replace(/<pre.*?>/g, '');
data = data.replace(/<PRE.*?>/g, '');
data = data.replace("<PRE>", '');
data = data.replace("</PRE>", '');
data = data.replace("<pre>", '');
data = data.replace("</pre>", '');
data = jQuery.parseJSON(data);
ajaxLoadEnd();
layer.alert(data.message);
}
});
}else{
layer.alert('上傳檔案格式有誤!預設支援xls/xlsx');
}
});
2,後臺用MultipartFile來接受前臺傳過來的檔案,
例如:public Object saveGoods(@RequestParam(value="uploadFile") MultipartFile myfile, HttpServletRequest request) {
MultipartHttpServletRequest multipartHttpservletRequest = (MultipartHttpServletRequest) request;
myfile = multipartHttpservletRequest.getFile("uploadFile");
if (myfile != null) {
uploadFilePath = saveAttachFile(myfile);//上傳檔案返回檔案路徑
}
saveAttachFile(){
File logo = new File(newFilePath);
multipartFile.transferTo(logo);上傳檔案
}
//獲取匯入模板
String goodsTemplateXMLPath = getRealPath()+ TemplatePathInterface.leadingin_goodsTemplateXML;
// 構建xml檔案輸入流
InputStream inputXML = new BufferedInputStream(new FileInputStream(goodsTemplateXMLPath));
// 繫結xml檔案
XLSReader reader = ReaderBuilder.buildFromXML(inputXML);
// 構建檔案輸入流
InputStream inputXLS = new BufferedInputStream(new FileInputStream(uploadFilePath));//根據路徑讀取檔案
List<Goods> goodses = new ArrayList<Goods>();
Map beans = new HashMap();
beans.put("goodses", goodses);
// 通過XSLReader 的read方法,它會自動對映pojo類,得到資料集合
reader.read(inputXLS, beans);
List<Goods> goodsList = new ArrayList<Goods>();
for (Goods progoods : goodses) {
goods = new Goods();
goodsList.add(goods);
}
// 批量儲存商品資訊goodsService.save(tenantId, goodsList);
};
二,匯出
1,前臺頁面
例如://匯出資訊(匯出選中的)
$("#exportList").click(function () {
window.location.href="${base}/weipu/download/orderModeByTimeExport?data="+dataRows;
})
//匯出資訊(匯出所有的)
$("#exportList").click(function(){
var property = $('#property').val();
var keyword = $("#keyword").val();
$.fileDownload('${base}/weipu/download/goodsList?property='+property+'&keyword='
+keyword)
.done(function () { layer.alert('下載成功!'); })
.fail(function () { layer.alert('下載失敗!'); });
});
2.後臺匯出的方法:
@RequestMapping(value = "goodsList", method = { RequestMethod.GET })
@ResponseBody
public void goodsList(HttpServletRequest request, HttpServletResponse response, Model model) {
String tenantId = getCurrentUser().getTenantId();
String property =request.getParameter("property");
String keyword =request.getParameter("keyword");
String isMarketable = request.getParameter("isMarketable");
Criteria criteria = new Criteria();
if(StringUtils.isNotEmpty(property)&&StringUtils.isNotEmpty(keyword)){
if(property.equals("brand")){
criteria.add(Restrictions.like("b.name", "%"+keyword+"%"));
}else if(property.equals("tag")){
criteria.add(Restrictions.like("t.name", "%"+keyword+"%"));
}else if(property.equals("category")){
criteria.add(Restrictions.like("c.name", "%"+keyword+"%"));
}else{
criteria.add(Restrictions.like("g."+property, "%"+keyword+"%"));
}
}
if (isMarketable != null && !"".equals(isMarketable)) {
criteria.add(Restrictions.eq("isMarketable", isMarketable));
}
criteria.add(Restrictions.group("g.id"));
List<Goods> list=new ArrayList<Goods>();
try {
list = goodsService.goodsListExport(tenantId, criteria);
} catch (Exception e1) {
e1.printStackTrace();
}
/*****list查詢結束******/
String fileExtName = "xls";
String time = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()).toString();
String newFileName = time + String.format("%04d", new Random().nextInt(1000)) + "." + fileExtName;
String downDir = request.getServletContext().getRealPath("/") + "/down";// WEB-INF
String downLoadFilePath = downDir + File.separator + newFileName;
File downLoadFile = new File(downLoadFilePath);
if (!downLoadFile.getParentFile().exists()) {
downLoadFile.mkdirs();
}
// 建立工作表與sheet的引用
WritableWorkbook workbook = null;
try {
if (!downLoadFile.exists()) {
downLoadFile.createNewFile();
}
OutputStream os = new FileOutputStream(downLoadFile);
workbook = Workbook.createWorkbook(os);
// 建立第一頁的sheet
WritableSheet sheet1 = workbook.createSheet("商品詳情表", 0); // 可新增第一個工作
// 檔案第一行寫入Title
String titleContent = "序號#商品編號#條形碼#全名稱#銷售價#品牌#分銷佣金比例#庫存#商品分類#是否上架#商品描述";
String[] title = titleContent.split("#");
for (int i = 0; i < title.length; i++) {
// Label(列號,行號 ,內容 )
Label label = new jxl.write.Label(i, 0, title[i]);
sheet1.addCell(label);
}
int j = 1;
if(list.size()>0){
for (Goods map : list) {
Label label0 = new jxl.write.Label(0, j, String.valueOf(j));
sheet1.addCell(label0);
Label label1 = new jxl.write.Label(1, j, map.getSn());
sheet1.addCell(label1);
Label label2 = new jxl.write.Label(2, j, map.getBarcode());
sheet1.addCell(label2);
Label label3 = new jxl.write.Label(3, j, map.getFullName());
sheet1.addCell(label3);
Label label4 = new jxl.write.Label(4, j, String.valueOf(map.getPrice()));
sheet1.addCell(label4);
Label label5 = new jxl.write.Label(5, j, map.getBrandId());
sheet1.addCell(label5);
if(null!=map.getPoint()){
Double point=map.getPoint()*100;
Label label6 = new jxl.write.Label(6, j, point+"%");
sheet1.addCell(label6);
}else{
Label label6 = new jxl.write.Label(6, j, "0%");
sheet1.addCell(label6);
}
Label label7 = new jxl.write.Label(7, j, String.valueOf(map.getStock()));
sheet1.addCell(label7);
Label label8 = new jxl.write.Label(8, j, map.getCategoryPath());
sheet1.addCell(label8);
Label label9 = new jxl.write.Label(9, j, isMarketableMap.get(String.valueOf(map.getIsMarketable())));
sheet1.addCell(label9);
Label label10= new jxl.write.Label(10, j, map.getDescription());
sheet1.addCell(label10);
j++;//換行
}
}
// ****讀取資料,寫入檔案****//
workbook.write();// 輸出到檔案
} catch (FileNotFoundException ex) {
logger.error("資料寫入檔案時,發生異常:", ex);
} catch (IOException ex) {
logger.error("資料寫入檔案時,發生異常:", ex);
} catch (WriteException ex) {
logger.error("資料寫入檔案時,發生異常:", ex);
} catch (Exception ex) {
logger.error("資料寫入檔案時,發生異常:", ex);
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (Exception e) {
logger.error("關閉檔案寫入流時,發生異常:", e);
}
}
}
try {
String contentType = "application/octet-stream";
String storeName = "商品管理" + newFileName;
String realName = newFileName;
if (downLoadFile.exists()) {
FileOperateUtil.downloadex(request, response, downLoadFilePath, contentType, storeName, realName);
}
} catch (Exception e) {
logger.error("匯出報表時,發生異常:", e);
}
}
public static void downloadex(HttpServletRequest request,
HttpServletResponse response,String downLoadFilePath,String contentType, String storeName,
String realName) throws Exception {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
long fileLength = new File(downLoadFilePath).length();
response.setContentType(contentType);
response.setHeader("Content-disposition", "attachment; filename="
+ new String(realName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadFilePath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
}
解析模板
<?xml version="1.0" encoding="UTF-8"?>
<workbook>
<worksheet name="Sheet1">
<!-- 開始行數,和結束行數。把EXCEL表中的前兩排直接幹掉-->
<section startRow="0" endRow="4" />
<!-- 下面是一行的模版,獲取一行,之後的行數就按這個模版來獲取-->
<!-- items是集合的名稱。-->
<loop startRow="5" endRow="5" items="goodses" var="goods"
varType="net.viservice.entity.weipu.Goods">
<section startRow="5" endRow="5">
<!-- 所屬分類 -->
<mapping cell="A6">goods.categoryId</mapping>
<!-- 分類路徑 -->
<mapping cell="B6">goods.barcode</mapping>
<!-- 商品名稱 -->
<mapping cell="C6">goods.name</mapping>
<!-- 商品編號 -->
<mapping cell="D6">goods.sn</mapping>
<!-- 成本價 -->
<mapping cell="E6">goods.cost</mapping>
<!-- 所屬品牌 -->
<mapping cell="F6">goods.brandId</mapping>
<!-- 計量單位 -->
<mapping cell="G6">goods.unit</mapping>
<!-- 重量 -->
<mapping cell="H6">goods.weight</mapping>
<!-- 搜尋關鍵字 -->
<mapping cell="I6">goods.keywords</mapping>
<!-- 銷售價 -->
<mapping cell="J6">goods.price</mapping>
<!-- 市場價 -->
<mapping cell="K6">goods.marketPrice</mapping>
<!-- 庫存數量 -->
<mapping cell="L6">goods.stock</mapping>
<!-- 是否上架 -->
<mapping cell="M6">goods.isMarketable</mapping>
<!-- 是否置頂 -->
<mapping cell="N6">goods.isTop</mapping>
<!-- 是否首頁 -->
<mapping cell="O6">goods.isIndex</mapping>
<!-- 是否全球購-->
<mapping cell="P6">goods.isGlobal</mapping>
<!-- 是否微信 -->
<mapping cell="Q6">goods.isWx</mapping>
<!-- 商品介紹 -->
<mapping cell="R6">goods.introduction</mapping>
</section>
<loopbreakcondition>
<rowcheck offset="0">
<cellcheck offset="0" />
</rowcheck>
<!--迴圈到值為空的時候結束 -->
</loopbreakcondition>
</loop>
</worksheet>
</workbook>