Java POI 导出EXCEL

1、写成了通过工具包,拿来即可用

ps:如果要加属性只需要在里面加一点代码即可

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class ExcelUtil {

    /**
     * 
     * @param res
     * @param title 对应的列标题
     * @param exportData 需要导出的数据
     * @param fileds 列标题对应的实体类的属性
     * @throws IOException
     */
    public static void exportExcel(HttpServletResponse res, List<String> title,
            List exportData, String fileds[]) throws IOException {
        // 1.创建一个workbook,对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 2.在workbook中添加一个sheet,对应Excel中的一个sheet
        HSSFSheet sheet = wb.createSheet("new sheet");
        // 3.在sheet中添加表头第0行,老版本poi对excel行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 4.创建单元格,设置值表头,设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        // 居中格式
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 设置表头
        for (int i = 0; i < title.size(); i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(title.get(i));
            cell.setCellStyle(style);
        }
        int size = 2;
        // 循环将数据写入Excel
        for (int j = 0; exportData != null && !exportData.isEmpty()
                && j < exportData.size(); j++) {
            Class clazz = exportData.get(j).getClass();
            String[] contents = new String[fileds.length];
            for (int i = 0; fileds != null && i < fileds.length; i++) {
                String filedName = toUpperCaseFirstOne(fileds[i]);
                Object obj = null;
                try {
                    Method method = clazz.getMethod(filedName);
                    method.setAccessible(true);
                    obj = method.invoke(exportData.get(j));
                } catch (Exception e) {

                }
                String str = String.valueOf(obj);
                if (str == null || str.equals("null"))
                    str = "";
                contents[i] = str;
            }
            size++;
            row = sheet.createRow(size);
            for (int n = 0; n < contents.length; n++) {
                // 将生成的单元格添加到工作表中
                row.createCell(n).setCellValue(contents[n]);
            }
        }
        //获取当前列的宽度,然后对比本列的长度,取最大值  
        for (int columnNum = 0; columnNum <= fileds.length; columnNum++)  
        {  
            int columnWidth = sheet.getColumnWidth(columnNum) / 256;  
            for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++)  
            {  
                Row currentRow;  
                //当前行未被使用过  
                if (sheet.getRow(rowNum) == null)  
                {  
                    currentRow = sheet.createRow(rowNum);  
                }  
                else   
                {  
                    currentRow = sheet.getRow(rowNum);  
                }  

                if(currentRow.getCell(columnNum) != null)  
                {  
                    Cell currentCell = currentRow.getCell(columnNum);  
                    int length = currentCell.toString().getBytes("GBK").length;  
                    if (columnWidth < length + 1)  
                    {  
                        columnWidth = length + 1;  
                    }  
                }  
            }  
            sheet.setColumnWidth(columnNum, columnWidth * 256);  //设置宽度
        } 
        // 使用浏览器下载
        String fileName = "数据导出表";
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数,可以打开下载页面
        res.reset();
        res.setContentType("application/vnd.ms-excel;charset=utf-8");
        res.setHeader("Content-Disposition", "attachment;filename="
                + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = res.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

    }

    /**
     * 将第一个字母转换为大写字母并和get拼合成方法
     * 
     * @param origin
     * @return
     */
    private static String toUpperCaseFirstOne(String origin) {
        StringBuffer sb = new StringBuffer(origin);
        sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
        sb.insert(0, "get");
        return sb.toString();
    }
}

提一下前台调用

<a href="#" onclick="exportData()" class="easyui-linkbutton" iconCls="icon-save">导出</a>

js

/**
 * 导出功能
 */
function exportData() {
    var exportURL=basePath + "/dustDataSelAction.do?action=export";
    //var path = encodeURI('${sd_graduateThesis.path}', "UTF-8");
    var xhLx=$("#xhLxComb").combobox('getValue');
    var gn=$("#gnCombobox").combobox('getValue');
    var start=$('#startTime').datetimebox('getValue');

    //使用form表单来发送请求 1.method属性用来设置请求的类型——post还是get 2.action属性用来设置请求路径。
    var form = $("<form>");// 定义一个form表单
    form.attr("style", "display:none");
    form.attr("target", "");
    form.attr("method", "post"); // 请求类型
    form.attr("action", exportURL); // 请求地址

    var input1 = $("<input>");
    input1.attr("type", "hidden");
    input1.attr("name", "xhLxComb");
    input1.attr("value", xhLx);
    form.append(input1);
    var input2 = $("<input>");
    input2.attr("type", "hidden");
    input2.attr("name", "gnId");
    input2.attr("value", gn);
    form.append(input2);
    var input3 = $("<input>");
    input3.attr("type", "hidden");
    input3.attr("name", "startTime");
    input3.attr("value", start);
    form.append(input3);

    $("body").append(form);// 将表单放置在web中
    form.submit();// 表单提交
    form.remove();
}
over了
注意:

1.如果报这个错误

 getWriter() has already been called for this response(异常解决)

通过response.reset(); 刷新可能存在一些未关闭的getWriter().
我已经在代码写出来了,再写一遍是为了提醒自己不要再犯这样的错误
2.用这个需要导入poi的jar文件,官网官网:http://poi.apache.org
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值