excel导出,项目实际运用案例

一,通过servlet方式:
package com.management.bim114.database.servlet;

import com.management.bim114.datastatistics.entity.LearnSummary;
import com.management.bim114.datastatistics.entity.Vo.DataStatisticsReq;
import com.management.bim114.datastatistics.entity.Vo.DataStatisticsRsp;
import com.management.bim114.datastatistics.service.LearnSummaryService;
import com.management.bim114.datastatistics.utils.AuthServiceUtils;
import com.management.bim114.filemanage.constant.ConstantCategoryBim114;
import com.management.bim114.huawei.common.ResultCode;
import com.management.bim114.huawei.common.constants.StaticNumber;
import com.management.bim114.huawei.common.utils.;
import com.management.bim114.huawei.database.entity.TenantListModel;
import com.management.bim114.huawei.inf.restful.request.DesktopBillingInfoReq;
import com.management.bim114.huawei.inf.restful.vo.ExportDesktopBillingInfos;
import com.management.bim114.huawei.servlet.UnusedVMsExcelServlet;
import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.
;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
*统计分析里面的用户信息的导出
*/
public class UserInfoExcelServlet extends HttpServlet {

/**
 * 引入日志对象
 */
private static Logger logger = LoggerFactory.getLogger(UserInfoExcelServlet.class);
/**
 * 导出Excel公用方法类
 */
private ExportExcelCommonMethod commonMethod = new ExportExcelCommonMethod();


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取请求参数toenId userId
    String toenId ="";
    String userId = "";
    String[] data = request.getHeader("Cookie").split(";");
    for (int i = 0 ; i <data.length ; i++ ) {
        if(data[i].contains("token_id")){
           toenId = data[i].split("=")[1];
        }
        if(data[i].contains("userName")){
           userId = data[i].split("=")[1];
        }
    }
    String userAgent = request.getHeader("User-Agent");
    //参数校验
    if (null == toenId|| null ==userId) {
        logger.error(ErrorCodeUtils.getErrorCodeDesc(ResultCode.NO_PERMISSION.getCode()));
    }

// //权限校验
// if(!authService.authPermission(toenId,null)){
// logger.error(ErrorCodeUtils.getErrorCodeDesc(ResultCode.NO_PERMISSION.getCode()));
// }
request.setCharacterEncoding(“utf-8”);
response.setCharacterEncoding(“utf-8”);
//准备文件名
String sheetName = commonMethod.getSheetName(“表名”);
//准备表头
String[] sheetTitles={“列名”,“列名”,“列名”,“列名”,“列名”};
//准备数据
DataStatisticsReq req = new DataStatisticsReq();
req.setTokenId(toenId);
//对关键字编码
List<对象> list = dao.getall();
// 输出流
OutputStream outputStream = null;
try {
// 清空response
response.reset();
response.setContentType(StaticNumber.EXCEL_CONTENT_TYPE);
response.addHeader(StaticNumber.CONTENT_DISPOSITION_KEY, commonMethod.getContentDispositionKey(userAgent, sheetName));

        outputStream = response.getOutputStream();
        // 将数据存入Excel并写入输出流
        ExportExcel<对象> exportExcel = new ExportExcel<对象>();
        boolean bCreateExcelFileSuccess = exportExcel.createExcelFileForUserInfo(sheetName, sheetTitles, list, outputStream, DateUtil.DATETIME_PATTERN);
        if(bCreateExcelFileSuccess){
            // 设置response的Header
            outputStream.flush();

        }else{
            logger.error("创建失败");
        }
    }catch (Exception exception) {
        logger.error("Failed to download the generated temporary files for exporting. ", exception);
    }finally {
        // 关闭输出流
        if (null != outputStream) {
            try {
                outputStream.close();
            } catch (IOException e) {
                logger.error("Failed to close the outputStream. ", e);
            }
        }
    }
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    super.doPost(req, resp);
}

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    WebApplicationContext appCtx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    learnSummaryService = BeanFactoryUtils.beanOfTypeIncludingAncestors(appCtx,对象.class);
}

}

二,创建excel

public boolean createExcelFileForUserInfo(String sheetName, String[] headers, List<对象> list, OutputStream out, String pattern) {

    // 创建Excel文件是否成功
    boolean bCreateExcelFileSuccess = true;

    // 声明一个工作薄
    SXSSFWorkbook workbook = new SXSSFWorkbook(ROW_ACCESS_WINDOW_SIZE);

    // 生成一个表格
    Sheet sheet = workbook.createSheet(sheetName);

    // 设置默认列宽
    sheet.setDefaultColumnWidth(DEFAULT_COLUMN_WIDTH);

    // 生成并设置边框样式
    XSSFCellStyle borderStyle = getBorderStyle(workbook);

    // 生成并设置数字列单元格的样式
    XSSFCellStyle numberCellStyle = getBorderStyle(workbook);
    numberCellStyle.setAlignment(XSSFCellStyle.ALIGN_RIGHT);

    // 产生表格标题行
    fillHeaderCell(headers, workbook, sheet.createRow(StaticNumber.FIRST_INDEX));

    if (!CollectionUtils.isEmpty(list)) {
        // 行号
        int rowNum = StaticNumber.INTEGER_DEFAULT_VALUE;
        for (对象 data:list) {
            Row row = sheet.createRow(++rowNum);
            int iColumnNum = StaticNumber.INTEGER_DEFAULT_VALUE;

            //中文名
            if(StringUtils.isEmpty(data.getCnName())){
                iColumnNum = fillCell(borderStyle, row, iColumnNum, "", null);
            }else{
                iColumnNum = fillCell(borderStyle, row, iColumnNum, data.getCnName(), null);
            }
            //部门
            if(StringUtils.isEmpty(data.getDepartmentName())){
                iColumnNum = fillCell(borderStyle, row, iColumnNum, "", null);
            }else {
                iColumnNum = fillCell(borderStyle, row, iColumnNum, data.getDepartmentName(), null);
            }//总学习时长
            if( StringUtils.isEmpty(data.getTotalStudyTime())){
                iColumnNum = fillCell(borderStyle, row, iColumnNum, "0", null);
            }else {
                iColumnNum = fillCell(borderStyle, row, iColumnNum, data.getTotalStudyTime().toString(), null);
            }
            //总积分
            if(StringUtils.isEmpty(data.getTotalIntegral())){
                iColumnNum = fillCell(borderStyle, row, iColumnNum, "0", null);
            }else{
                iColumnNum = fillCell(borderStyle, row, iColumnNum, data.getTotalIntegral().toString(), null);
            }
            //总课程
            if( StringUtils.isEmpty(data.getCourseNum())){
                iColumnNum = fillCell(borderStyle, row, iColumnNum, "0", null);
            }else {
                iColumnNum = fillCell(borderStyle, row, iColumnNum, data.getCourseNum().toString(), null);
            }
        }
    }
    // 向xls文件中写数据并关闭输出流
    try {
        workbook.write(out);
    } catch (IOException e) {
        logger.error("Failed to export: ", e);
        bCreateExcelFileSuccess = false;
    }
      return bCreateExcelFileSuccess;
}


三,重点说明
通过doget方式request在数据传输时,如果有汉字可能会出现乱码的情况,需要处理一下:
String keyword = new String(request.getParameter("参数名").getBytes("iso-8859-1"), "utf-8");
乱码后会出现对集合查询的结果产生影响。
建议后面可以写在dopost方法里面。这个方法里汉字不会出现乱码的情况。

猜你喜欢

转载自blog.csdn.net/m0_37997811/article/details/89704508