码迷,mamicode.com
首页 > 其他好文 > 详细

用jxl导出Excel

时间:2017-05-02 22:09:48      阅读:361      评论:0      收藏:0      [点我收藏+]

标签:new   r.java   update   字符集   osi   check   tin   居中   技术分享   

断断续续,终于把这个简单的功能实现了。

本身花的有效时间也不多,但是陆续出现好多蛋疼的问题,归根结底是自己程序功底不深厚,尤其对Java流理解不透彻。

还好今天时间充足,磨得我背疼不已的时候,终于把它整完了。

这里首先介绍下背景:SSM框架(前端easyui)、POI因为乱码问题被pass掉、五一假期又没有花时间,不得不赶紧换个API把他整出来。

功能大致是这样的:

技术分享

点击按钮导出所有的(不经分页的)数据到Excel中。

busiAccept.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@ include file="../../../common.jsp"%>
 4 <!-- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> -->
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>业务受理报表</title>
 9     <link id="easyuiTheme" rel="stylesheet" type="text/css" href="../../../jquery-easyui/themes/metro/easyui.css" />
10     <link rel="stylesheet" type="text/css" href="../../../jquery-easyui/themes/icon.css"/>
11     <link rel="stylesheet" type="text/css" href="../../../style/css/main.css"/>
12     <link rel="stylesheet" type="text/css" href="../../../style/css/publicCss/dialogTable.css"/>
13     <link rel="stylesheet" type="text/css" href="../../../style/css/qm/SiProdForms.css" />
14     <style type="text/css">
15         body {
16             margin: 0 0 0 0;
17             height: 100%;
18         }
19     </style>
20 </head>
21 
22 <body>
23     <div id="tt">
24         <div title="业务报表">
25             <table id="test" style="height: 100%;"></table>
26         </div>
27         <div title="受理详情">
28             <table id="test2" style="height: 100%;"></table>
29         </div>
30     </div>
31     <div id=‘tb‘ style="padding:5px;">
32         <table >
33             <tr>
34             <td style="font-size: 12px;">分公司:</td>
35             <td><input id="queryRegion" class="easyui-combobox" type="text" ></td><!-- value="选择分公司" -->
36             <td style="font-size: 12px;">受理时间:</td>
37             <td><input id="startTime" value="请选择开始时间" editable="false" class="easyui-datebox"></input></td>
38             <td style="font-size: 12px;"></td>
39             <td><input id="endTime" value="请选择结束时间" editable="false" class="easyui-datebox"></input></td>
40             <td><a href="#" class="easyui-linkbutton" iconcls="icon-search" onclick="query()" plain="true">查询</a></td>
41             </tr>
42         </table >
43     </div>
44     <script type="text/javascript" src="../../../jquery-easyui/jquery.min.js"></script>   
45     <script type="text/javascript" src="../../../jquery-easyui/jquery.easyui.min.js"></script>   
46     <script type="text/javascript" src="../../../jquery-easyui/locale/easyui-lang-zh_CN.js"></script>
47     <script type="text/javascript" src="../../../js/qm/userInfo/busiAccept.js"/>
48 </body>
49 <script type="text/javascript">
50 </script>
51 </html>

common.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 2 <%@ page import="java.util.*"  %>
 3 <%@ page import="java.io.*"  %>
 4 <%
 5     HttpSession s1 = request.getSession(); 
 6 %>
 7 <%
 8     //获取rest访问地址
 9     String realPath = request.getRealPath("");
10     realPath = realPath.replaceAll("\\\\", "/");
11     int last = realPath.lastIndexOf("/");
12     String subPath = realPath.substring(0, last);
13     int lastSecond = subPath.lastIndexOf("/");
14     subPath = subPath.substring(0, lastSecond);
15     
16     int lastls=subPath.lastIndexOf("/");
17     subPath = subPath.substring(0, lastls);
18     
19     //System.out.println("subPath="+subPath);
20     String path = subPath+"/aim-conf/aim-web.properties";
21     Properties props = new Properties();
22     File file = new File(path);
23     InputStream in = new FileInputStream(file);
24     props.load(in);
25     String fileUrl = props.getProperty("fileUrl");
26     String host = props.getProperty("host");
27 %>
28 <input type="hidden" id="fileUrl" value="<%=fileUrl %>"/>
29 <input type="hidden" id="host" value="<%=host %>"/>
30 <input type="hidden" id="loginId_" value="<%=s1.getAttribute("loginId") %>"/>

busiAccept.jsp中引入common.jsp主要是为了busiAccept.js在请求后台的时候带过去必要的参数:loginId(在session中)、请求地址(在配置文件中)

busiAccept.js(重点在toVoid()中)

  1 /**
  2  * 
  3  */
  4 document.write("<script type=‘text/javascript‘ src=‘../../../WebTool.js‘></script>");
  5 
  6 var queryRegion;
  7 var startTime;
  8 var endTime;
  9 $(function(){
 10     addTabs();
 11     $(‘#tt‘).tabs(‘disableTab‘, 1);
 12     datagridTest(false,‘‘);
 13     
 14     var registClient = {
 15         onComplete : function(args) {
 16             if(args.resultCode=="0000"){
 17                 $(‘#queryRegion‘).combobox({
 18                     editable:false,
 19                     valueField : ‘regionId‘,
 20                     textField : ‘regionName‘,
 21                     data:args.rows
 22                 });
 23             }else{
 24                 $(‘#queryRegion‘).combobox({
 25                     editable:false,
 26                     valueField : ‘regionId‘,
 27                     textField : ‘regionName‘
 28                 });
 29             }
 30         },
 31         onError : function(error) {
 32             console.info("error");
 33             console.info(error);
 34         },
 35         onException : function(status, errorInfo, hint) {
 36             console.info("errorInfo");
 37             console.info(errorInfo);
 38         },
 39         onFinally:function(){
 40         }
 41     };
 42     var info=‘{"servicName":"getRegionList","regionType":"2"}‘;
 43     $u.webutil.doPost("../../../AWCCI",info, true, registClient);
 44         
 45 });
 46 
 47 function addTabs(){
 48     $(‘#tt‘).tabs({
 49         width:parent.$(‘#tabs‘).width,
 50         fit:true
 51     });
 52 }
 53 
 54 function datagridTest(cd,paras){
 55     var url = ‘‘;
 56     var queryParam = {};
 57     if(cd){
 58         url = ‘../../../public‘;
 59         queryParam = {"servicName":"busiAccept","data":paras};
 60     }
 61     $(‘#test‘).datagrid({
 62         fit:true,
 63         url:url,
 64         queryParams:queryParam,
 65         border:false,
 66         singleSelect:true,
 67         fitColumns:true,
 68         checkOnSelect:false,
 69         columns:[[
 70             {field:‘ck‘,checkbox:true, width:20},
 71             {field:‘companyId‘,title:‘分公司‘,width:100,hidden:‘true‘},
 72             {field:‘companyName‘,title:‘分公司‘,width:100},
 73             {field:‘acceptSystem‘,title:‘受理系统‘,hidden:‘true‘},
 74             {field:‘acceptSystemName‘,title:‘受理系统‘,width:100},
 75             {field:‘prodId‘,title:‘基础产品‘,width:100,hidden:‘true‘},
 76             {field:‘prodName‘,title:‘基础产品‘,width:100},
 77             {field:‘offerId‘,title:‘业务类型‘,width:100,hidden:‘true‘},
 78             {field:‘offerName‘,title:‘业务类型‘,width:100},
 79             {field:‘totalNum‘,title:‘总计‘,width:100,formatter:function(value,row,index){
 80                 return "<a href=‘#‘ onclick=‘detail("+value+","+row.companyId+","+row.acceptSystem+","+row.prodId+","+row.offerId+")‘>"+value+"<font color=‘#cc0000‘>详情</font></a>";
 81             }}
 82         ]],
 83         toolbar:‘#tb‘,
 84         pagination:true,
 85         pageSize:10,
 86         pageList :[5,10,15]
 87     });
 88     var pager = $(‘#test‘).datagrid(‘getPager‘);// 得到datagrid的pager对象
 89     pager.pagination({
 90         showPageList : false,
 91         buttons : [ {
 92             text : "导出Excel",
 93             iconCls : "icon-add",
 94             handler : "toVoid"
 95         } ],
 96         onBeforeRefresh : function() {
 97             alert(‘before refresh‘);
 98             return true;
 99         }
100     });
101 }
102 
103 // 导出Excel
104 function toVoid() {
105     if(queryRegion != null && queryRegion != ‘‘ && startTime != null && startTime != ‘‘ && endTime != null && endTime != ‘‘){
106         var paras = ‘{‘;
107         paras += ‘"startTime":"‘+startTime+‘"‘;
108         paras += ‘,"endTime":"‘+endTime+‘"‘;
109         if(queryRegion!=‘-1‘&&queryRegion!=-1){
110             paras += ‘,"companyId":"‘+queryRegion+‘"‘;
111         }
112         paras += ‘}‘;
113         
114         /*var registClient = {
115             onComplete : function(args) {
116                 if (args.resultCode == "0000") {
117                     $.messager.alert("操作提示", args.resultMessage, "info");//提示已经导出到某个位置
118                 } else {
119                     $.messager.alert("操作提示", args.resultMessage,"error");
120                 }
121             },
122             onError : function(error) {
123                 console.info("error");
124                 console.info(error);
125             },
126             onException : function(status, errorInfo, hint) {
127                 console.info("errorInfo");
128                 console.info(errorInfo);
129             },
130             onFinally : function() {
131                 // $u.dialog_util.hideDialog("","loading");
132             }
133         };
134         pvar info = ‘{"servicName":"exportExcel","data":‘ + paras + ‘}‘;
135         $u.webutil.doPost("../../../AWCCI", info, true, registClient);*/
136         
137         var host = $(‘#host‘).val();
138         var loginId = $(‘#loginId_‘).val();
139         //alert(host+","+loginId);
140         var export_path = "http://"+host
141                 + "/aim-api/busiAcc/exportExcel?loginId="+loginId+"&startTime="
142                 + startTime + "&endTime=" + endTime;
143         window.open(export_path);
144         
145     }else{
146         $.messager.alert("操作提示", "查询数据之后才能导出","error");
147     }
148     
149 };
150 
151 function query(){
152     var regionId = $(‘#queryRegion‘).combobox(‘getValue‘);
153     if(regionId != null && regionId != ‘‘){
154         var paras = ‘{‘;
155         var startTime0 = $(‘#startTime‘).datebox(‘getValue‘);
156         var endTime0 = $(‘#endTime‘).datebox(‘getValue‘);
157         if(getDate(startTime0)-getDate(endTime0)>0){
158              $.messager.alert("操作提示","开始时间应小于结束时间","error");
159              return;
160         }
161         startTime = startTime0 + " 00:00:00";
162         endTime = endTime0 + " 23:59:59";
163         paras += ‘"startTime":"‘+startTime+‘"‘;
164         paras += ‘,"endTime":"‘+endTime+‘"‘;
165         queryRegion = regionId;
166         if(regionId!=‘-1‘&&regionId!=-1){
167             paras += ‘,"companyId":"‘+regionId+‘"‘;
168         }
169         paras += ‘}‘;
170         datagridTest(true,paras);
171     }else{
172         $.messager.alert("操作提示","请选择分公司","error");
173          return;
174     }
175     
176 }
177 
178 function getDate(date){
179     var dates = date.split("-");
180     var dateReturn = ‘‘;
181     //alert("数组长度:"+dates.length);
182     for(var i=0; i<dates.length; i++){
183         dateReturn+=dates[i];
184     }
185     return dateReturn;
186 }
187 
188 function detail(value,companyId,acceptSystem,prodId,offerId){
189     if(!value){
190         $.messager.alert("操作提示", "无详情信息","info");
191         return;
192     }
193     var paras = ‘{"companyId":"‘+companyId+‘","startTime":"‘+startTime+‘","endTime":"‘+endTime+‘","acceptSystem":"‘+acceptSystem+‘","prodId":"‘+prodId+‘","offerId":"‘+offerId+‘"}‘;
194     datagrid2(paras);
195     $(‘#tt‘).tabs(‘select‘,‘受理详情‘);
196     $(‘#tt‘).tabs(‘enableTab‘, 1);
197     $(‘#tt‘).tabs(‘select‘, 1);
198     /*var tab = $(‘#tt‘).tabs(‘getTab‘,1);
199     $(‘#tt‘).tabs(‘update‘, { 
200         tab: tab, 
201         options: { 
202             title: ‘详情列表(待处理工单数)‘
203         } 
204     });*/
205 }
206 
207 function datagrid2(paras){
208     $(‘#test2‘).datagrid({
209         fit:true,
210         url:‘../../../public‘,
211         queryParams:{"servicName":"busiAcceptDetail","data":paras},
212         border:false,
213         singleSelect:true,
214         fitColumns:true,
215         checkOnSelect:false,
216         columns:[[
217             {field:‘ck‘,checkbox:true, width:20},
218             {field:‘orderId‘,title:‘业务流水号‘,width:100},
219             {field:‘fromOrderId‘,title:‘对端流水号‘,width:100},
220             {field:‘accNbr‘,title:‘逻辑号码‘,width:100},
221             {field:‘acceptWorkerName‘,title:‘受理员工名称‘,width:100},
222             {field:‘acceptRelaPhone‘,title:‘受理员工联系电话‘,width:100},
223             {field:‘acceptTime‘,title:‘受理时间‘,width:100},
224             {field:‘createTime‘,title:‘创建时间‘,width:100},
225             {field:‘finishTime‘,title:‘完成时间‘,width:100},
226             {field:‘orderState‘,title:‘定单状态‘,width:60,formatter:function(value,row,index){
227                 switch (value) {
228                 case "0":
229                     return "正常";
230                 case "1":
231                     return "注销";
232                 case "2":
233                     return "开通失败";
234                 default:
235                     return "";
236                 }
237             }},
238             {field:‘dealState‘,title:‘处理状态‘,width:60,formatter:function(value,row,index){
239                 switch (value) {
240                 case "0":
241                     return "流程中";
242                 case "1":
243                     return "已完工";
244                 case "2":
245                     return "未生成流程";
246                 case "3":
247                     return "直接竣工";
248                 default:
249                     return "";
250                 }
251             }}
252         ]],
253         pagination:true,
254         pageSize:10,
255         pageList :[5,10,15]
256     });
257 }
143 window.open(export_path);是原生的请求方式,以前我都是用别人写好的包装后的方法……
BusiAcceptController.java(略去import,另外实际上我的注解没有用,因为请求方式原生的)
 1 @Controller
 2 @RequestMapping("/busiAcc")
 3 public class BusiAcceptController {
 4     Logger logger  =  Logger.getLogger(BusiAcceptController.class );
 5     @Resource
 6     private BusiAcceptService busiAcceptService;
 7     @Resource
 8     private AimBaseService aimBaseService;
 9 
10     @RequestMapping(value="/exportExcel",produces = "text/html;charset=UTF-8")
11     public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
12         Long beginTime = System.currentTimeMillis();
13         /*设置格式为text/json */
14         response.setContentType("text/json"); 
15         /*设置字符集为‘UTF-8‘*/
16         response.setCharacterEncoding("UTF-8");
17         JSONObject resJsonObj = new JSONObject(); //返回json对象
18         //JSONObject reqJsonObj = new JSONObject(); //请求json对象
19         String requestInfo="";//请求信息
20         String resultInfo =""; //返回信息
21         String resultCode ="0000";//返回代码
22         String serviceName ="exportExcel";
23         
24          TsmOperLog tsmOperLog = new TsmOperLog();
25          tsmOperLog.setCmdType(serviceName);
26 
27         String companyId = request.getParameter("companyId");
28         String startTime =request.getParameter("startTime");
29         String endTime = request.getParameter("endTime");
30         
31         logger.info("接受WEB参数-----------------="+companyId+"--"+startTime+"----------"+endTime);
32         
33 
34         String excelName = "业务处理报表ss";
35         response.setContentType("application/vnd.ms-excel");
36         response.setHeader("Content-Disposition", "attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
37          try {
38              busiAcceptService.exportExcel2(companyId,startTime,endTime,response);//bWorkbook = 
39          } catch (Exception e) {
40              logger.info("导出业务受理报表数据异常");
41              resultCode = "9025";
42              resJsonObj.put("resultCode", resultCode);
43              resJsonObj.put("resultMessage", "导出业务受理报表数据异常" + e.getMessage());
44              resultInfo = resJsonObj.toString();
45              tsmOperLog.setResultCode(resultCode);
46              //tsmOperLog.setRequestInfo(requestInfo);
47              tsmOperLog.setResponseInfo(resultInfo);
48              aimBaseService.insertTsmOperLog(tsmOperLog);
49              logger.info("Time:["
50                      + new SimpleDateFormat("yyyyMMddHHmmssSSS")
51                              .format(new Date()) + "],处理耗时:"
52                      + (System.currentTimeMillis() - beginTime) + ",resultInfo:"
53                      + resultInfo);
54              AimUtils.writeData(response, resultInfo);
55              return;
56          }
57          if (resJsonObj != null) {
58              resultCode = "0000";
59              resJsonObj.put("resultCode", resultCode);
60              resJsonObj.put("resultMessage", "导出业务受理报表数据成功");
61          }
62          resultInfo = resJsonObj.toString();
63 
64          tsmOperLog.setResultCode(resultCode);
65          tsmOperLog.setRequestInfo(requestInfo);
66          tsmOperLog.setResponseInfo(resultInfo);
67          aimBaseService.insertTsmOperLog(tsmOperLog);
68 
69          logger.info("Time:["
70                  + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
71                  + "],处理耗时:" + (System.currentTimeMillis() - beginTime)
72                  + ",resultInfo:" + resultInfo);
73          AimUtils.writeData(response, resultInfo);
74     }
75 
76 }

BusiAcceptService.java

1 public interface BusiAcceptService {
2     
3     public void exportExcel2(String companyId, String startTime, String endTime,HttpServletResponse response) throws ParseException, UnsupportedEncodingException;
4 
5 }

BusiAcceptServiceImpl.java

  1 @Service("BusiAcceptService")
  2 public class BusiAcceptServiceImpl implements BusiAcceptService{
  3     Logger logger = Logger.getLogger(BusiAcceptServiceImpl.class);
  4     @Resource
  5     private AimBaseDao aimBaseDao;
  6     @Resource
  7     private TbmOrderQueueHisDao tbmOrderQueueHisDao;
  8     @Resource
  9     private CacheDataService cacheDataService;
 10 
 11     @Override
 12     public void exportExcel2(String companyId, String startTime,
 13             String endTime,HttpServletResponse response) throws ParseException, UnsupportedEncodingException {
 14         //将数据导出到Excel  
 15         WritableWorkbook bWorkbook = null;
 16         TbmOrderQueueHis tbmOrderQueueHis = new TbmOrderQueueHis();
 17         if(companyId != null && !companyId.equals("")){
 18             tbmOrderQueueHis.setCompanyId(Integer.valueOf(companyId));
 19         }
 20         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 21         tbmOrderQueueHis.setCreateTime(sdf.parse(startTime));
 22         tbmOrderQueueHis.setFinishTime(sdf.parse(endTime));
 23 
 24         List<TbmOrderQueueHis> tbmOrderQueueHisList = tbmOrderQueueHisDao.selectByConditions4Excel(tbmOrderQueueHis);
 25         try {  
 26             // 创建Excel对象  
 27             //根据传进来的file对象创建可写入的Excel工作薄  
 28             OutputStream os = response.getOutputStream();  
 29             bWorkbook = Workbook.createWorkbook(os);
 30             //bWorkbook = Workbook.createWorkbook(new File("C:/Users/CY/Desktop/业务处理报表ss.xls")); 
 31             // 通过Excel对象创建一个选项卡对象  
 32             WritableSheet sheet = bWorkbook.createSheet("sheet1", 0);
 33             //设置表格指定列的列宽
 34             sheet.setColumnView(0, 14);
 35             sheet.setColumnView(1, 12);
 36             sheet.setColumnView(2, 25);
 37             sheet.setColumnView(3, 20);
 38             
 39             //往工作簿中插入数据,设定字体:微软雅黑,24,加粗
 40             // 创建字体对象
 41             WritableFont titleFont = new WritableFont(WritableFont.createFont("微软雅黑"), 24, WritableFont.NO_BOLD);
 42             WritableFont contentFont = new WritableFont(WritableFont.createFont("楷体 _GB2312"), 12, WritableFont.NO_BOLD);
 43             WritableCellFormat titleFormat = new WritableCellFormat(titleFont);
 44             WritableCellFormat contentFormat = new WritableCellFormat(contentFont);
 45             WritableCellFormat contentFormat2 = new WritableCellFormat(contentFont);
 46             
 47             contentFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
 48             // 设置格式居中对齐
 49             titleFormat.setAlignment(jxl.format.Alignment.CENTRE);
 50             contentFormat.setAlignment(jxl.format.Alignment.CENTRE);
 51             contentFormat2.setAlignment(jxl.format.Alignment.CENTRE);
 52 
 53             // 将定义好的单元格绑定数据添加到工作簿中
 54             sheet.mergeCells(0, 0, 4, 0); // 合并单元格A-G列共7列
 55             sheet.addCell(new Label(0, 0, "业务受理情况", titleFormat));
 56             sheet.addCell(new Label(0, 1, "受理时间", contentFormat2));
 57             sheet.mergeCells(1, 1, 4, 1); // 合并单元格B-G列共7列
 58             sheet.addCell(new Label(1, 1, startTime+"至"+endTime, contentFormat2));
 59 
 60             String th[] = { "分公司", "受理系统", "基础产品", "业务类型", "总计"};
 61             for (int i = 0; i < th.length; i++) {
 62                 sheet.addCell(new Label(i, 2, th[i], contentFormat2));
 63                 //            new Label(列, 行, 值, 样式)
 64             }
 65             
 66             //使用循环将数据读出  
 67             if (tbmOrderQueueHisList != null && tbmOrderQueueHisList.size() > 0) {
 68                 for (int i = 0; i < tbmOrderQueueHisList.size(); i++) {
 69                     TbmOrderQueueHis tbmOrderQueueHis0 = tbmOrderQueueHisList.get(i);
 70                     String companyName=cacheDataService.getValidTableCondition("TsmRegion","regionId", String.valueOf(tbmOrderQueueHis0.getCompanyId())).getString("regionName");
 71                     System.out.println("companyName:"+companyName);
 72                     String systemName=cacheDataService.getValidTableCondition("TsmSystemManage","systemId", String.valueOf(tbmOrderQueueHis0.getAcceptSystem())).getString("systemName");
 73                     String prodName=cacheDataService.getValidTableCondition("TpmBaseProduct","baseProdId", String.valueOf(tbmOrderQueueHis0.getProdId())).getString("baseProdName");
 74                     String offerName=cacheDataService.getValidTableCondition("TpmServiceOffer","offerId", String.valueOf(tbmOrderQueueHis0.getOfferId())).getString("offerName");
 75                     
 76                     Label label=new Label(0,i+3,companyName,contentFormat);
 77                     Label label1=new Label(1,i+3,systemName,contentFormat);
 78                     Label label2=new Label(2,i+3,prodName,contentFormat);
 79                     Label label3=new Label(3,i+3,offerName,contentFormat);
 80                     Label label4=new Label(4,i+3,String.valueOf(tbmOrderQueueHis0.getTotalNum()),contentFormat);
 81                     
 82                     sheet.addCell(label);
 83                     sheet.addCell(label1);
 84                     sheet.addCell(label2);
 85                     sheet.addCell(label3);
 86                     sheet.addCell(label4);
 87                 }
 88             }
 89             // 写如目标路径
 90             bWorkbook.write();
 91             try {
 92                 bWorkbook.close();
 93                 //关闭流  
 94                 os.flush();
 95                 os.close();
 96             } catch (WriteException | IOException e) {  
 97                 e.printStackTrace();  
 98             }
 99         } catch (Exception e) {  
100             e.printStackTrace();  
101         } finally {
102         }
103     }
104 }

pom.xml

1 <!-- 导出Excel -->
2         <dependency>
3             <groupId>net.sourceforge.jexcelapi</groupId>
4             <artifactId>jxl</artifactId>
5             <version>2.6.12</version>
6         </dependency>

另外这个pom导入jar包也很奇怪,明明是http://220.181.85.249:8081/nexus/index.html#welcome里边先找到jxl然后把代码版本信息等拷进来。但是往往这样都只能找到低版本,反而要去网上搜索jxl+maven,找到引入高版本的那种jar的pom代码帖进来,进而会直接下载高版本jar

另外BusiAcceptServiceImpl.java中,

 92                 bWorkbook.close();
 94                 os.flush();
 95                 os.close();
流的关闭顺序不对会导致导出空白的Excel。
另外用封装的请求方式$u.webutil.doPost("../../../AWCCI", info, true, registClient);为什么不行(到底行不行)还有待测试,老火的是家里外网速度太慢。

技术分享

点击导出之后,浏览器会自动下载Excel文件到浏览器的下载目录。

再回味一下关键代码:

 15         WritableWorkbook bWorkbook = null;
 26             // 创建Excel对象  
 27             //根据传进来的file对象创建可写入的Excel工作薄  
 28             OutputStream os = response.getOutputStream();  
 29             bWorkbook = Workbook.createWorkbook(os);
bWorkbook.write();

对于流,还需要熟悉……

 

用jxl导出Excel

标签:new   r.java   update   字符集   osi   check   tin   居中   技术分享   

原文地址:http://www.cnblogs.com/lovesufang/p/6798490.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!