Excel import and export in JeeSite

  In various management systems, data import and export are frequently used functions, usually in Excel and CSV formats. If it is in the process of learning, it is best to implement the functions of data import and export by yourself. However, in the project, it is better to call the ready-made functions. Recently, I have been using an open source project called JeeSite for secondary development, so I will record the process of importing and exporting data from Excel for this project. JeeSite provides a good import and export function of Excel, which hides many underlying implementations. The import and export of Excel data can be completed through simple routine steps. For those who haven't used JeeSite, you don't need to read further, because the following code is related to the secondary development of JeeSite, and does not do the secondary development of JeeSite. The following code is useless to you, here is a friendly reminder to avoid wasting your precious time.

 

Import and export steps

  Whether it is the JeeSite system, other systems or systems written by yourself, for the data import and export function, the first thing to determine is which data fields to import and export, then provide an import template, write the import and export functions, and finally in the The operation mode of import and export is provided on the page for users to use.

 

Define import and export fields

  When importing and exporting data, it will first determine which key fields of the data to be imported and exported. After determining the fields, the data queried through the database will be exported one by one according to the fields, or read in one by one through the read Excel. In JeeSite, after determining the fields to be imported and exported, the annotations can be used in the entity class of JeeSite. The annotation methods are as follows:

1 @ExcelField(title="列名1", align=2, sort=10)

  Defined in this way, the fields in the class can be associated with Excel columns, including column names and sorting. Examples are as follows:

copy code
1 @ExcelField(title="名称", align=2, sort=10) 
2 public String getName() {
3     return name;
4 }
5 
6 @ExcelField(title="年龄", align=2, sort=20)  
7 public String getAge() {
8     return age;
9 }
copy code

  Adding the @ExcelField annotation to the getter method of the entity class completes the association between the Excel column name and the entity class field.

 

Excel data export function

  The export function in JeeSite is completely a routine. Only three simple lines can complete an export function. First, set the export file name, then query the export data, and finally call ExportExcel() to complete the Excel export. The example code is as follows:

copy code
 1 @RequestMapping(value = "export", method=RequestMethod.POST)
 2 public String exportFile(Info info, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
 3     try {
 4         String fileName = "信息数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
 5         // 调用获取数据的方法 ... 省略 6         new ExportExcel("信息数据", Info.class).setDataList(page).write(response, fileName).dispose();
 7         return null;
 8     } catch (Exception e) {
 9         addMessage(redirectAttributes, "信息数据导出失败!失败信息:"+e.getMessage());
10     }
11     return "redirect:" + adminPath + "/info/Info/list?repage";
12 }
copy code

  return后的地址,根据实际的Controller来填写。

 

导入模板

  导入模板是用来给系统使用者在导入数据时使用的,有了导入模板就相当于有了一个导入的规范,确定需要导入哪些列来让使用者填入。在JeeSite中,导入模板并不用事先提供一个Excel,而是通过代码直接生成一个Excel文件,Excel文件中的列也是由前面实体类中确定的,这样的好处是,当列的数量改变时不用人为的去替换修改Excel,因为它是有代码生成的。导入模板的代码例子如下:

copy code
 1 @RequestMapping(value = "import/template")
 2 public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
 3     try {
 4         String fileName = "信息数据导入模板.xlsx";
 5         List<Info> list = Lists.newArrayList(); 
 6         list.add(new Info());
 7         new ExportExcel("信息数据", Info.class, 2).setDataList(list).write(response, fileName).dispose();
 8         return null;
 9     } catch (Exception e) {
10         addMessage(redirectAttributes, "导入模板下载失败!失败信息:"+e.getMessage());
11     }
12     return "redirect:" + adminPath + "/info/Info/list?repage";
13 }
copy code

  此处return后的地址,也是根据实际的Controller来填写。

 

Excel数据导入功能

  用户下载好数据模板后,将相应的数据填写好,就可以进行数据的导入了。数据的导入是对Excel中的数据不断进行遍历和保存的一个过程,代码虽然比导出要长,但是也完全是套路,代码如下:

copy code
 1 @RequestMapping(value = "import", method=RequestMethod.POST)
 2 public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
 3     
 4     try {
 5         int successNum = 0;     // 导入成功计数
 6         int failureNum = 0;     // 导入失败计数
 7         StringBuilder failureMsg = new StringBuilder();
 8         ImportExcel ei = new ImportExcel(file, 1, 0);
 9         
10         List<Info> list = ei.getDataList(Info.class);
11         
12         for ( Info info : list ) {
13             // ...
14             if ( ... ) {  // 导入条件的判断
15                 // 符合导入条件
16                 // 保存 ... 方法省略
17                 successNum++;
18             } else {
19                 // 不符合导入条件
20                 failureMsg.append("<br/>名字 " + info.getName() + " 已存在; ");
21                 failureNum++;
22             }
23         }
24 
25         if (failureNum>0){
26             failureMsg.insert(0, ",失败 " + failureNum + " 条信息,导入信息如下:");
27         }
28         
29         addMessage(redirectAttributes, "已成功导入 " + successNum + " 条片区信息" + failureMsg);
30         
31     } catch (Exception e) {
32         // TODO Auto-generated catch block
33         e.printStackTrace();
34     }
35     
36     return "redirect:" + adminPath + "/info/Info/list?repage";
37 }
copy code

 

添加导入导出按钮

  在页面上添加两个按钮,分别是导入和导入按钮,代码如下:

1 <li class="btns">
2     <input id="btnExport" class="btn btn-primary" type="button" value="导出"/>
3     <input id="btnImport" class="btn btn-primary" type="button" value="导入"/>
4 </li>

 

导入时弹出的窗口

  在点击“导入”按钮时会弹出一个窗口,窗口中可以提供导入文件选择,也可以下载导入模板。代码如下:

copy code
1 <div id="importBox" class="hide">
2     <form id="importForm" action="${ctx}/info/Info/import" method="post" enctype="multipart/form-data"
3         class="form-search" style="padding-left:20px;text-align:center;" onsubmit="loading('正在导入,请稍等...');"><br/>
4         <input id="uploadFile" name="file" type="file" style="width:330px"/><br/><br/>  
5         <input id="btnImportSubmit" class="btn btn-primary" type="submit" value="   导    入   "/>
6         <a href="${ctx}/info/Info/import/template">下载模板</a>
7     </form>
8 </div>
copy code

  在代码中,需要修改action和href后的具体路径才能保证数据的提交,和模板下载的地址,具体地址根据自己项目中的Controller来进行替换。

 

控制导入导出按钮的JS代码

  对于导出按钮来说,需要通过action来讲数据进行导出,对于导入按钮来说只是需要把导入时显示的窗口显示出来即可。相关代码如下:

copy code
 1 $(document).ready(function() {        
 2     $("#btnExport").click(function(){
 3         top.$.jBox.confirm("确认要导出片区数据吗?","系统提示",function(v,h,f){
 4             if(v=="ok"){
 5                 $("#searchForm").attr("action","${ctx}/info/Info/export");
 6                 $("#searchForm").submit();
 7             }
 8         },{buttonsFocus:1});
 9         top.$('.jbox-body .jbox-icon').css('top','55px');
10     });
11     $("#btnImport").click(function(){
12         $.jBox($("#importBox").html(), {title:"导入数据", buttons:{"关闭":true}, 
13             bottomText:"导入文件不能超过5M,仅允许导入“xls”或“xlsx”格式文件!"});
14     });
15 });
copy code

 

  对于需要使用JeeSite开源项目进行二次开发的话,上面的代码算是一个比较详细的笔记了,如果不使用JeeSite开源项目的话,上面的代码就没有什么用处了。这篇笔记留个自己和需要的人吧。我还会陆续的发一些关于JeeSite的二次开发的笔记。

 

http://news.zis3531.cn/
http://news.cyj2776.cn/
http://news.bpj4889.cn/
http://news.dvu3043.cn/
http://news.vrc3090.cn/
http://news.ecx0415.cn/
http://news.oyt3985.cn/
http://news.mfu9569.cn/
http://news.lev2249.cn/
http://news.bdw7316.cn/
http://news.yyf8629.cn/
http://news.baq6972.cn/
http://news.xcd5039.cn/
http://news.bed0568.cn/
http://news.hzg6462.cn/
http://news.dec9975.cn/
http://news.hyt6211.cn/
http://news.ysz1764.cn/
http://news.xah7645.cn/
http://news.rlo9176.cn/
http://news.iaz8522.cn/
http://news.mng2781.cn/
http://news.axs9870.cn/
http://news.csv7317.cn/
http://news.kpq2047.cn/
http://news.igm8568.cn/
http://news.cgn5379.cn/
http://news.axz7045.cn/
http://news.rfz4575.cn/
http://news.cxb4532.cn/
http://news.qri2046.cn/
http://news.zps7191.cn/
http://news.zcl0267.cn/
http://news.ozn1702.cn/
http://news.zbb7727.cn/
http://news.vtl3405.cn/
http://news.zht3189.cn/
http://news.zzl7747.cn/
http://news.abd5921.cn/
http://news.hch9349.cn/
http://news.hwp3498.cn/
http://news.wll1115.cn/
http://news.rol3427.cn/
http://news.akb6775.cn/
http://news.giy4971.cn/
http://news.tyo9948.cn/
http://news.uzh3227.cn/
http://news.mfc7569.cn/
http://news.otm3953.cn/
http://news.ewh1005.cn/
http://news.iip1291.cn/
http://news.dyg4913.cn/
http://news.ase4727.cn/
http://news.uqx4260.cn/
http://news.sif0574.cn/
http://news.sdb0307.cn/
http://news.thg4282.cn/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325775693&siteId=291194637