Excel导出

ExportExcelUtil.java

公共工具类

package com.ningpai.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 导出Excel工具类
 *
 * @author ChenDaiMing
 * @since 2016/1/14
 */
public class ExportExcelUtil {

    /**
     * Excel导出
     * @author ChenDaiMing
     * @param response    response
     * @param title       Excel标题                                                              <br>
     *                      用户信息列表                                                      <br><br>
     * @param columnsName Excel列名称                                                            <br>
     *                      String[] rowsName = new String[]{"ID","账号","姓名"};             <br><br>
     * @param dataList    导出的数据<br>
     *                      List< Object[] >  dataList = new ArrayList< Object[] >();            <br>
     *                      Object[] obj = new Object[3];                                        <br>
     *                      obj[0] = ID数据;                                                     <br>
     *                      obj[1] = 账号数据;                                                    <br>
     *                      obj[2] = 姓名数据;                                                   <br>
     */
    public static void export(HttpServletResponse response, String title, String[] columnsName, List<Object[]> dataList) throws IOException {
        //创建工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建工作表sheet
        HSSFSheet sheet = workbook.createSheet(title);
        //产生表格标题行
        HSSFRow row = sheet.createRow(0);

        HSSFCell cellTitle = row.createCell(0);
        //sheet样式定义
        //获取列头样式对象
        HSSFCellStyle columnTopStyle = ExportExcelUtil.getColumnTopStyle(workbook);
        HSSFCellStyle style = ExportExcelUtil.getStyle(workbook);

        //合并
        sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (columnsName.length - 1)));
        cellTitle.setCellStyle(columnTopStyle);
        cellTitle.setCellValue(title);

        //定义所需列数
        int columnNum = columnsName.length;
        //创建列头行
        HSSFRow rowName = sheet.createRow(2);
        // 将列头设置到sheet的单元格中
        for (int i = 0; i < columnNum; i++) {
            HSSFCell cellName = rowName.createCell(i);                  //创建列头对应个数的单元格
            cellName.setCellType(HSSFCell.CELL_TYPE_STRING);             //设置列头单元格的数据类型
            HSSFRichTextString text = new HSSFRichTextString(columnsName[i]);
            cellName.setCellValue(text);                                 //设置列头单元格的值
            cellName.setCellStyle(columnTopStyle);                       //设置列头单元格样式
        }

        //将查询出的数据设置到sheet对应的单元格中
        for (int i = 0; i < dataList.size(); i++) {

            Object[] obj = dataList.get(i);//遍历每个对象
            HSSFRow tempRow = sheet.createRow(i + 3);//创建所需的行数

            for (int j = 0; j < obj.length; j++) {
                HSSFCell cell = null;   //设置单元格的数据类型
                if (j == 0) {
                    cell = tempRow.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(i + 1);
                } else {
                    cell = tempRow.createCell(j, HSSFCell.CELL_TYPE_STRING);
                    if (!"".equals(obj[j]) && obj[j] != null) {
                        cell.setCellValue(obj[j].toString()); //设置单元格的值
                    }
                }
                cell.setCellStyle(style);  //设置单元格样式
            }
        }
        //让列宽随着导出的列长自动适应
        for (int colNum = 0; colNum < columnNum; colNum++) {
            int columnWidth = sheet.getColumnWidth(colNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                //当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }
                if (currentRow.getCell(colNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(colNum);
                    if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            if (colNum == 0) {
                sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
            } else {
                sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
            }
        }
        //输出到客户端进行下载
        OutputStream out = null;
        if (workbook != null) {
                String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
                String headStr = "attachment; filename=" + fileName;
                response.setContentType("APPLICATION/OCTET-STREAM");
                response.setHeader("Content-Disposition", headStr);
                out = response.getOutputStream();
                workbook.write(out);
                out.flush();
                out.close();
        }

    }

    /*
      * 列头单元格样式
      */
    private static HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 11);
        //字体加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        return style;
    }

    /*
    * 列数据信息单元格样式
    */
    private static HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        return style;
    }


}

 使用Controller.java

 /**
     * 导出销售额Excel
     * @param response
     * @param startTime
     * @param endTime
     * @author ChenDaiMing
     */
    @RequestMapping("/exportSaleMoney")
    public void exportSaleMoney(HttpServletResponse response,String startTime, String endTime){
        String title = "销售额统计";
        String[] columnsName = {"序号","日期","PC端销售额","移动端销售额","总销售额"};
        List<String> payTime = DateUtil.getAllDateBetween2Date(startTime, endTime);
        List<Order> orderListAll = orderService.querySaleMoneyByDay(startTime, endTime,null);
        List<Order> orderListPC = orderService.querySaleMoneyByDay(startTime, endTime,"0");
        List<Order> orderListMobile = orderService.querySaleMoneyByDay(startTime, endTime,"1");
        //总计list
        List<BigDecimal> totalList = new ArrayList<BigDecimal>();
        List<BigDecimal> pcTotalList = new ArrayList<BigDecimal>();
        List<BigDecimal> mobileTotalList = new ArrayList<BigDecimal>();
        //总价
        BigDecimal total = new BigDecimal(0);
        BigDecimal pcTotal = new BigDecimal(0);
        BigDecimal mobileTotal = new BigDecimal(0);

        //为导出的每日订单计算销售额,无销售额的为零
        for(String time : payTime) {
            boolean flag = false;
            //计算总销售额
            for(Order order : orderListAll) {
                if(time.equals(DateUtil.dateToString(order.getPayTime(), "yyyy-MM-dd"))) {
                    flag = true;
                    totalList.add(order.getDayMoney());
                    total = total.add(order.getDayMoney());
                }
            }
            if(!flag){
                totalList.add(new BigDecimal(0));
            }
            flag = false;

            //计算PC总销售额
            for(Order order : orderListPC) {
                if(time.equals(DateUtil.dateToString(order.getPayTime(), "yyyy-MM-dd"))) {
                    flag = true;
                    pcTotalList.add(order.getDayMoney());
                    pcTotal = pcTotal.add(order.getDayMoney());
                }
            }
            if(!flag){
                pcTotalList.add(new BigDecimal(0));
            }
            flag = false;


            //计算移动端总销售额
            for(Order order : orderListMobile) {
                if(time.equals(DateUtil.dateToString(order.getPayTime(), "yyyy-MM-dd"))) {
                    flag = true;
                    mobileTotalList.add(order.getDayMoney());
                    mobileTotal = mobileTotal.add(order.getDayMoney());
                }
            }
            if(!flag){
                mobileTotalList.add(new BigDecimal(0));
            }
            flag = false;
        }
        //获取查询的订单数据
        List<Object[]> dataList = new ArrayList<>();

        //根据查询日期进行导出数据
        for (int i = 0; i <payTime.size(); i++) {
            Object[] objs = new Object[columnsName.length];
            objs[0] = i;
            objs[1] = payTime.get(i);
            objs[2] = pcTotalList.get(i);
            objs[3] = mobileTotalList.get(i);
            objs[4] = totalList.get(i);
            dataList.add(objs);
        }
        //销售额总计
        Object[] totalObjs = new Object[columnsName.length];
        totalObjs[0] = "";
        totalObjs[1] = "";
        totalObjs[2] = pcTotal.toString();
        totalObjs[3] = mobileTotal.toString();
        totalObjs[4] = total.toString();
        dataList.add(totalObjs);
        try {
            ExportExcelUtil.export(response,title,columnsName,dataList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

猜你喜欢

转载自chendaiming.iteye.com/blog/2271461