以前是用Poi做Excel的操作、最近一个项目用jxl来做!现在项目完成了、做做总结!
首先呢、需要的当然是jxl的.jar包!---------->jxl.jar<------------
代码:因为这次的导出业务不怎么复杂稍微把对Excel导出的操作提了一下
- /**
- * @author 旦旦而学
- * @param file 文件对象
- * @param objData 导出内容数组
- * @param sheetName 导出工作表的名称
- * @param columns 导出Excel的表头数组
- * @return
- */
- public static int exportToExcel_3(File file, Object[] objData, String sheetName,
- String[] columns) {
- int flag = 0;
- //声明工作簿jxl.write.WritableWorkbook
- WritableWorkbook wwb;
- try {
- //根据传进来的file对象创建可写入的Excel工作薄
- wwb = Workbook.createWorkbook(file);
- /*
- * 创建一个工作表、sheetName为工作表的名称、"0"为第一个工作表
- * 打开Excel的时候会看到左下角默认有3个sheet、"sheet1、sheet2、sheet3"这样
- * 代码中的"0"就是sheet1、其它的一一对应。
- * createSheet(sheetName, 0)一个是工作表的名称,另一个是工作表在工作薄中的位置
- */
- WritableSheet ws = wwb.createSheet(sheetName, 0);
- //创建单元格样式
- WritableCellFormat wcf = new WritableCellFormat();
- //背景颜色设置为"那什么"色
- wcf.setBackground(Colour.YELLOW);
- /*
- * 这个是单元格内容居中显示
- * 还有很多很多样式
- */
- wcf.setAlignment(Alignment.CENTRE);
- //判断一下表头数组是否有数据
- if (columns != null && columns.length > 0) {
- //循环写入表头
- for (int i = 0; i < columns.length; i++) {
- /*
- * 添加单元格(Cell)内容addCell()
- * 添加Label对象Label()
- * 数据的类型有很多种、在这里你需要什么类型就导入什么类型
- * 如:jxl.write.DateTime 、jxl.write.Number、jxl.write.Label
- * Label(i, 0, columns[i], wcf)
- * 其中i为列、0为行、columns[i]为数据、wcf为样式
- * 合起来就是说将columns[i]添加到第一行(行、列下标都是从0开始)第i列、样式为什么"色"内容居中
- */
- ws.addCell(new Label(i, 0, columns[i], wcf));
- }
- //判断表中是否有数据
- if (objData != null && objData.length > 0) {
- //循环写入表中数据
- for (int i = 0; i < objData.length; i++) {
- //我这里直接用Object来接收了、因为情况特殊没有javaBean很痛苦、转换过后得到一条记录
- Object obj[] = (Object[]) objData[i];
- //将得到的记录写入Cell(单元格)中
- for (int j = 0; j < obj.length; j++) {
- //这里不引用样式了、j为列、(i+1)为行、因为表头占去了一行、所以后面的就+1
- ws.addCell(new Label(j, i + 1, String.valueOf(obj[j])));
- }
- }
- }
- //写入Exel工作表
- wwb.write();
- //关闭Excel工作薄对象
- wwb.close();
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- System.out.println(ex.getMessage());
- flag = 1;
- }
- return flag;
- }
- /**
- * 下载excel
- * @author 旦旦而学
- * @param response
- * @param url 文件存放路径,如: request.getRealPath("/");
- * @param filename 文件名 ,如:20110808.xls
- * @param listData 数据源
- * @param sheetName 表头名称
- * @param columns 列名称集合,如:{物品名称,数量,单价}
- */
- public static void exportexcle_3(HttpServletResponse response,String url,String filename,Object[] listData,String sheetName,String[] columns)
- {
- //根据传进来的文件路径、创建文件
- File file = new File(url + filename);
- //调用上面的方法、生成Excel文件
- exportToExcel_3(file, listData, sheetName, columns);
- //声明一个file对象
- File f=null;
- try {
- //根据刚刚的文件地址、创建一个file对象
- f = new File(url + filename);
- //如果文件不存在
- if (!f.exists()) {
- response.sendError(404, "File not found!");
- }
- //创建一个缓冲输入流对象
- BufferedInputStream br = new BufferedInputStream(
- new FileInputStream(f));
- byte[] buf = new byte[1024];
- int len = 0;
- response.reset(); // 非常重要
- response.setContentType("application/x-msdownload");
- response.setHeader("Content-Disposition", "attachment; filename="
- + f.getName());
- //创建输出流对象
- OutputStream outStream = response.getOutputStream();
- //开始输出
- while ((len = br.read(buf)) > 0)
- outStream.write(buf, 0, len);
- //关闭流对象
- br.close();
- outStream.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (f.exists()) {//下载完毕删除文件
- f.delete();
- }
- }
在Action中只需在获取完数据库中的数据过后直接调用上面的方法、并传入参数就Ok了!
- Object[] repObj = report.queryMaintainUnit(obj,pageInfo);
- String[] strArr = {"流水号","路段名","维护站名","所属系统",
- "故障等级","维护工区","派工时间","维修单位",
- "接修时间","处理结果","维修结果"};
- ExportDate expor = new ExportDate();
- expor.exportexcle_3(response,this.getUrl(),this.getFileName(),
- repObj,"维修单位明细表",strArr);
这是查询出来的数据:
Excel:
在加上分页功能过后、数据出了问题、当点击下一页的时候、会多出一列、这一列是Oracle数据库分页时添加的rownum列、1、2、3、4、5、6、这样!
因为我的数据在输出的时候没有用到javaBean、用的是数组、所以输出的时候、连后面的那一列也一起输出了!
这样需要判断一下、但是不知道为什么、第一页的时候rownum列不会出现、第二页还有后面的页rownum就会跑出来!
虽然占时解决了、但是害怕它哪天不高兴出点什么乱子就老火了!
-------------------------------------------
下面在来个直接Servlet的!
- /*
- * Excel文件名
- */
- private String fileName;
- public String getFileName() {
- this.setFileName("用户信息"+".xls");
- return fileName;
- }
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
- /*
- * 文件存储路径
- */
- private String url;
- public String getUrl(HttpServletRequest request) {
- File f = new File(request.getRealPath("/")+"ExcelData//");
- //如果文件不存在则创建文件夹
- if (!f.exists()) {
- f.mkdir();
- }
- this.setUrl(request.getRealPath("/")+"ExcelData//");
- return url;
- }
- public void setUrl(String url) {
- this.url = url;
- }
- /**
- * 导出用户信息
- * @param request
- * @param response
- * @return
- * @throws Exception
- */
- public void exportBoss_Users(HttpServletRequest request, HttpServletResponse response )throws Exception{
- String productnoId = request.getParameter("productnoId");
- String customnoId = request.getParameter("customno");
- List<UsersInfo> userList = new UsersInfoImpl().findBoss_UsersInfoAll(productnoId, customnoId);
- File file = null;
- PrintWriter out = null;
- try{
- request.setCharacterEncoding("UTF-8");
- response.setContentType("text/html;charset=UTF-8");
- out = response.getWriter();
- file = new File(this.getUrl(request) + this.getFileName());
- WritableWorkbook wwb;
- wwb = Workbook.createWorkbook(file);
- WritableSheet ws = wwb.createSheet("用户信息Excel", 0);
- String[] columns = {"用户姓名","用户手机","用户性别","所属部门","累计消费值","创建时间","帐号状态"};
- for (int i = 0; i < columns.length; i++) {
- ws.addCell(new Label(i, 0, columns[i]));
- }
- for (int i = 0; i < userList.size(); i++) {
- UsersInfo users = userList.get(i);
- ws.addCell(new Label(0, i+1, users.getUsersName()));
- ws.addCell(new Label(1, i+1, users.getUsersPhone()));
- ws.addCell(new Label(2, i+1, users.getUsersSex()));
- ws.addCell(new Label(3, i+1, users.getUsersDept()));
- ws.addCell(new Label(4, i+1, users.getUsersSum()));
- ws.addCell(new Label(5, i+1, users.getUsersCreatedate()));
- int num = Integer.parseInt(users.getUsersStatus()+"");
- String stAry = "";
- switch (num) {
- case 1:
- stAry = "启用" ;
- break;
- case 2:
- stAry = "禁用" ;
- break;
- default:
- stAry = "注销" ;
- break;
- }
- ws.addCell(new Label(6, i+1, stAry));
- }
- wwb.write();
- wwb.close();
- BufferedInputStream br = new BufferedInputStream(
- new FileInputStream(file));
- byte[] buf = new byte[1024];
- int len = 0;
- response.reset(); // 非常重要
- response.setContentType("application/x-msdownload");
- response.setHeader("Content-Disposition", "attachment; filename="
- + new String(file.getName().getBytes(),"iso-8859-1"));
- OutputStream outStream = response.getOutputStream();
- while ((len = br.read(buf)) > 0)
- outStream.write(buf, 0, len);
- br.close();
- outStream.close();
- }catch(Exception ex){
- ex.printStackTrace();
- out.print("<script>alert('导出用户信息失败、请从试!');</script>");
- }finally{
- if (file.exists()) {//下载完毕删除文件
- file.delete();
- }
- if(out!=null){
- out.flush();
- out.close();
- }
- }
- }
以前用的是UUID文件名、没发现乱码这么一说。
今天导出的时候发现了乱码
什么utf、gbk都是浮云!
直接用:
- response.setHeader("Content-Disposition", "attachment; filename="
- + new String(file.getName().getBytes(),"iso-8859-1"));