1. 程式人生 > >JXL匯入/匯出

JXL匯入/匯出

近兩年技術沒有過細化總結,突然心血來潮,隨手來總結一些問題,廢話不多說,切入正題。

jxl匯入匯出這裡主要用的EXTJS+Sh

  •  前端:建立按鍵,呼叫觸發事件,根據觸發事件中url找到控制層相對應的路徑
  1. 按鍵

  2.js

/*
         * 匯入 
         */
        importItem : function() {
            Ext.QuickTips.init();
            Ext.onReady(function() {
                var form 
= new Ext.form.FormPanel({ baseCls : 'x-plain', labelWidth : 80, url : cfg.cxt +'/eplantrain/manage/upload/excel.sj', fileUpload : true, defaultType : 'textfield', items : [ { xtype:
'fileuploadfield', name: 'file', fieldLabel: '&nbsp&nbsp&nbsp檔名', labelWidth: 50, msgTarget: 'side', allowBlank: false, anchor: '90%', buttonText:
'選擇Excel檔案' },{ xtype: 'label', text: '(請選擇Excel匯入,注意錄入的欄位格式)', style:{ marginLeft:'10px' } } ] }); var win = new Ext.Window({ title : '上傳Excel', width : 400, height : 130, layout : 'fit', plain : true, bodyStyle : 'padding:5px;', buttonAlign : 'center', items : form, buttons : [ { text : '匯入', handler : function() { if (form.form.isValid()) { Ext.MessageBox.show({ title : '請等待', msg : '匯入中...', progressText : '', width : 300, progress : true, closable : false, animEl : 'loding' }); form.getForm().submit({ success : function(form, action) { listView.queryResItem(); Ext.Msg.alert("提示",action.result.msg); win.hide(); }, failure : function(form, action) { Ext.Msg.alert('警告',"Excel匯入失敗!"); win.hide(); } }); } } }, { text : '關閉', handler : function() { win.hide(); } } ] }); win.show(); }); }, /*匯出檔案*/ exportFile: function () { var sm = grid.getSelectionModel(); if (sm.getCount() == 0) { Ext.Mytip.msg('提示', '您尚未選擇要匯出的資料!'); return; } var ids = []; sm.each(function(r) { ids.push(r.data.id); }); // Ext.Msg.confirm('請確認', // '<span style="color:red"><b>提示:</b>確定匯出嗎?</span>', // function(btn,text) { // if (btn == 'yes') { // // Ext.Ajax.request({ // url :cfg.cxt + "/eplantrain/manage/underwrite_export.sj", // // success : function(response) { // // //window.location.href = cfg.cxt + "/eplantrain/manage/exports.sj"; // var rt = Ext.decode(response.responseText); // alert(111+response.responseText.success==true+rt); // if (rt.success) { // listView.queryResItem(); // Ext.Mytip.msg('提示', '匯出成功!'); // } else { // Ext.Mytip.msg('提示', rt.msg); // } // }, // failure : safetys.ajaxError, // params : { // "ids" : ids.join(',') // } // }); // } // }); window.location.href = cfg.cxt + "/eplantrain/manage/exports.sj?ids="+ids; },

 

  •  後臺程式碼

 

//匯出Excel****************************************
@SuppressWarnings("deprecation")
@RequestMapping("/exports")
@ResponseBody
public Msg exportFile(HttpServletResponse response,String ids) throws Exception {

Assert.isTrue(StringUtils.isNotBlank(ids), "引數錯誤!");
// 1.檔案下載響應頭
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + new String(("匯出Excel名").getBytes("gb2312"), "ISO-8859-1") + ".xls");

 

//response.setHeader("Content-Disposition", "attachment;filename=" + new String((edTemplate.getTemplateName() + "匯入模板").getBytes(), "ISO-8859-1") + ".xls");

// 2.響應到瀏覽器
WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());
// 建立工作簿sheet
WritableSheet sheet = workbook.createSheet("工作簿名", 0);

//設定字型;
WritableFont font2 = new WritableFont(WritableFont.ARIAL,14,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLUE);
WritableCellFormat cellFormat1 = new WritableCellFormat(font2);
//設定背景顏色;
cellFormat1.setBackground(Colour.PINK);
//設定邊框;
cellFormat1.setBorder(Border.ALL, BorderLineStyle.DASH_DOT);
//設定自動換行;
cellFormat1.setWrap(true);
//設定文字居中對齊方式;
cellFormat1.setAlignment(Alignment.CENTRE);
//設定垂直居中;
cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
// 3.設定column名(標題目錄,根據自己資料庫表字段命名)
String[] ts ={"法規或檔名稱","制定機關","文號","釋出時間","法規分類","層級","最近修訂時間","狀態","法規或檔案電子檔"};
Label label=null;
for(int i=0;i<ts.length;i++){
//x,y,第一行的列名
label=new Label(i,0,ts[i],cellFormat1);
//7:新增單元格
sheet.addCell(label);
}
// 4.把資料填充到工作簿中 呼叫service呼叫查詢資料庫
List<ZZcfg> list = zzcfgService.findz(ids);

try{
for (int i = 0, j = 1; i < list.size(); i++, j++) {
ZZcfg z = list.get(i);
//System.out.println(z);
//設定列寬
sheet.setColumnView(i, 16);
//重新設定部分列寬
sheet.setColumnView(3, 14);
sheet.setColumnView(6, 14);
sheet.setColumnView(7, 14);
//設定行高
sheet.setRowView(i, 350);
//設定字型的attribute
WritableFont font1=new WritableFont(WritableFont.createFont("楷體 _GB2312"), 12, WritableFont.NO_BOLD);
WritableCellFormat format1=new WritableCellFormat(font1);

sheet.addCell(new Label(0, j, z.getzName(),format1));
sheet.addCell(new Label(1, j, z.getForOrg(),format1));
sheet.addCell(new Label(2, j, z.gettNumber(),format1));

String applydate=z.getReleTime().toLocaleString().substring(0,9);
sheet.addCell(new Label(3, j, applydate,format1));
sheet.addCell(new Label(4, j, z.getFgfl(),format1));
sheet.addCell(new Label(5, j, z.getOrderNo(),format1));
String applydateq=z.getLastTime().toLocaleString().substring(0,9);
sheet.addCell(new Label(6, j, applydateq,format1));
sheet.addCell(new Label(7, j, z.getzStatus().toString(),format1));
sheet.addCell(new Label(8, j, z.getTextField(),format1));


}
}catch (Exception e){
e.printStackTrace();
}

// 5.寫入資料
workbook.write();
// 6.關閉資源
workbook.close();
return new Msg();

}
//匯入Excel****************************************
@RequestMapping("upload/excel")
public void importExcelPapaers(HttpServletRequest request, HttpServletResponse response, @RequestParam MultipartFile file) throws IOException,
JSONException {

JSONObject jo = new JSONObject();
response.setContentType("text/html;charset=utf-8");
if (file.isEmpty()) {
jo.put("success", true);
jo.put("msg", "匯入失敗,檔案不能為空!");
response.getWriter().print(jo.toString());
} else {
if ("application/vnd.ms-excel".equals(file.getContentType().toString())) {
//建立一個集合
List<ZZcfg> list = new ArrayList<ZZcfg>();
// 獲取Excel物件
Workbook book;
try {
book = Workbook.getWorkbook(file.getInputStream());
// 獲取Excel第一個選項卡物件
Sheet sheet = book.getSheet(0);
// 遍歷選項卡,第一行是表頭,所以索引數-1
for (int i = 0; i < sheet.getRows() - 1; i++) {
ZZcfg zz = new ZZcfg();
// 獲取第i+1行單元格物件
zz.setzName(sheet.getCell(0,i+1).getContents());
zz.setForOrg(sheet.getCell(1,i+1).getContents());
zz.settNumber(sheet.getCell(2,i+1).getContents());
//時間格式的轉換
try {
zz.setReleTime(new SimpleDateFormat("yyyy-MM-dd").parse(sheet.getCell(3,i+1).getContents()));
zz.setLastTime(new SimpleDateFormat("yyyy-MM-dd"). parse(sheet.getCell(6,i+1).getContents()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
zz.setFgfl(sheet.getCell(4,i+1).getContents());
zz.setOrderNo(sheet.getCell(5,i+1).getContents());
zz.setzStatus(sheet.getCell(7,i+1).getContents());
zz.setTextField(sheet.getCell(8,i+1).getContents());
list.add(zz);

}
for (int i = 0; i < list.size(); i++) {
zcfgService.save(list.get(i));
}
} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jo.put("success", true);
jo.put("msg", "匯入成功!");
response.getWriter().print(jo.toString());
} else {
jo.put("success", true);
jo.put("msg", "匯入失敗!");
response.getWriter().print(jo.toString());
}
}

 

}

 

 Impl

/新增
    @Override
    public ZZcfg save(ZZcfg entity) {
        this.merge(entity);
        return entity; 
    }
@Override
    public List<ZZcfg> findz(String ids) {

        
        ArrayList<ZZcfg> l = new ArrayList<ZZcfg>();
        if(ids.contains(",")){
        String[] tIds = StringUtils.split(ids,",");        
        for (int i = 0; i < tIds.length; i++) {    
                String id = StringUtils.trim(tIds[i]);
                ZZcfg pc = this.get(Long.valueOf(id));
                l.add(pc);
            }
        }else{
            ZZcfg ac = this.get(Long.parseLong(ids));
            l.add(ac);
        }
        for (int i = 0; i < l.size(); i++) {
            String a = l.get(i).getzName();
            
        }
        return l;
    }