導出excel工具類List Map String, Object 方式

package com.jx.erp.utils;

import com.alibaba.druid.util.StringUtils;
import com.jx.erp.exception.MyException;
import org.apache.poi.hssf.usermodel.*;

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

/**
 * excel根據
 */
public class ExcelUtils {

    public static HSSFWorkbook generateListContent(List<Map<String, Object>> mapList, String sheetName) {
        return generateListContent(mapList, sheetName, null);
    }

    public static HSSFWorkbook generateListContent(List<Map<String, Object>> mapList, String sheetName, HSSFWorkbook hssfWorkbook) {
        if (StringUtils.isEmpty(sheetName)) throw new MyException("sheet名稱不能爲空");
        if (hssfWorkbook == null) hssfWorkbook = new HSSFWorkbook();
        if (mapList == null) return hssfWorkbook;

        /**
         * 創建一個sheet
         */
        HSSFSheet sheet = hssfWorkbook.createSheet(sheetName);
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setDefaultColumnWidth(20);
        sheet.setDefaultRowHeightInPoints(20);
        /**
         * 創建單元格,並設置值表頭 設置表頭居中
         */
        HSSFCellStyle style = hssfWorkbook.createCellStyle();
        /**
         * 創建一個居中格式
         */
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFFont font = hssfWorkbook.createFont();
        //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        style.setFont(font);

        /**
         * row樣式1
         */
        HSSFCellStyle style1 = hssfWorkbook.createCellStyle();
        HSSFFont font1 = hssfWorkbook.createFont();
        font1.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        /**
         * row樣式2
         */
        HSSFCellStyle style2 = hssfWorkbook.createCellStyle();
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFFont font2 = hssfWorkbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        style2.setFont(font2);

        HSSFRow row;
        HSSFCell cell;
        int cellIndex;
        int rowIndex = 0;
        for (Map<String, Object> mapRow : mapList) {
            row = sheet.createRow(rowIndex);
            cellIndex = 0;
            for (Map.Entry<String, Object> entry : mapRow.entrySet()) {
                System.out.println(entry.getKey() + ":" + entry.getValue());
                cell = row.createCell(cellIndex);
                cell.setCellValue(entry.getValue() + "");
                if (rowIndex == 0) {
                    cell.setCellStyle(style2);
                } else {
                    cell.setCellStyle(style1);
                }
                cellIndex++;
            }
            rowIndex++;
        }

        return hssfWorkbook;
    }

    public static void write(HSSFWorkbook hssfWorkbook, String name, HttpServletResponse response) throws IOException {
        write(hssfWorkbook, name, null, response);
    }

    /**
     * 輸出流
     *
     * @param hssfWorkbook
     * @param name
     * @param suffix       後綴
     * @param response
     * @throws IOException
     */
    public static void write(HSSFWorkbook hssfWorkbook, String name, String suffix, HttpServletResponse response) throws IOException {

        if (suffix == null) suffix = "xls";

        OutputStream os = null;
        //將excel的數據寫入文件
        response.setContentType("octets/stream");
        String excelName = name;//文件名字
        //轉碼防止亂碼
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + "." + suffix);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            os = response.getOutputStream();
            hssfWorkbook.write(os);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("生成表格出錯");
        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }

    }

}

調用

/**
     * desc: 導出發票列表 param: contractId return: author: CDN date: 2019/7/11
     */
    @GetMapping("exportInvoce")
    public JsonResult exportInvoce(@RequestParam HashMap map, HttpServletResponse response) {
        logger.info("==================" + CommonUtils.generateUUID() + " TRANSACTION_NAME : " + LOG_ROUTE + "exportInvoce REQUEST_DATA : " + JSON.toJSONString(map));
        Map<String, Object> map1 = invoiceService.getListPage(map);

        if (map1.get("listNoPage") == null) {
            return JsonResult.buildSuccess(new ArrayList<String>());
        }
        List<Invoice> invoiceList = (List<Invoice>) map1.get("listNoPage");

        List<InvoiceListData> listData = new ArrayList<>();
        if (invoiceList.size() > 0) {
            for (Invoice invoice : invoiceList) {
                CompanyInfo companyInfo = companyInfoService.getById(invoice.getCompanyId());
                if (!StrUtils.isNullOrEmpty(companyInfo)) {
                    InvoiceListData invoiceListData = new InvoiceListData();
                    invoiceListData.setCompanyName(companyInfo.getCompanyName());
                    BeanUtils.copyProperties(invoice, invoiceListData);
                    listData.add(invoiceListData);
                }
            }
        } else {
            return JsonResult.buildSuccess(new ArrayList<String>());
        }
        Map<String, Object> respMap;
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (listData.size() > 0) {
            respMap = new LinkedHashMap<>();
            respMap.put("no", "發票號碼");
            respMap.put("code", "發票代碼");
            respMap.put("type", "發票類型");
            respMap.put("state", "發票狀態");
            respMap.put("customerCompany", "客戶公司");
            respMap.put("selfCompanyName", "我方公司");
            respMap.put("productName", "商品名稱");
            respMap.put("taxPrice", "稅額");
            respMap.put("sumPrice", "合計金額");
            respMap.put("taxSumPrice", "價稅合計");
            respMap.put("souceNo", "原發票號碼");
            respMap.put("souceCode", "原發票代碼");
            respMap.put("noticeNo", "通知單編碼");
            respMap.put("drawer", "開票人");
            respMap.put("openDate", "開票日期");
            respMap.put("cancelDate", "作廢人");
            respMap.put("customerNo", "客戶識別號");
            respMap.put("listId", "清單標識");
            mapList.add(respMap);
        } else {
            throw new MyException("暫無可導出的數據");
        }

        for (InvoiceListData aListData : listData) {
            respMap = new LinkedHashMap<>();

            if (!StrUtils.isNullOrEmpty(aListData
                    .getInvoiceNo())) {
                respMap.put("no", aListData.getInvoiceNo());
            } else {
                respMap.put("no", "");
            }
            if (!StrUtils.isNullOrEmpty(aListData.getCode())) {
                respMap.put("code", aListData.getCode());
            } else {
                respMap.put("code", "");
            }
            if (aListData.getType() > 0) {
                respMap.put("type", aListData.getType() == 1 ? "增值稅專票" : "增值稅普票");
            } else {
                respMap.put("type", "");
            }

            if (aListData.getState() > 0) {
                respMap.put("state", aListData.getState() == 1 ? "正常發票" : "異常發票");
            } else {
                respMap.put("state", "");
            }

            if (!StrUtils.isNullOrEmpty(aListData.getCustomerCompany())) {
                respMap.put("customerCompany", aListData.getCustomerCompany());
            } else {
                respMap.put("customerCompany", "");
            }
            if (aListData.getCompanyId() > 0) {
                CompanyInfo companyInfo = companyInfoService.getById(aListData.getCompanyId());
                if (StrUtils.isNullOrEmpty(companyInfo)) {
                    respMap.put("selfCompanyName", "");
                } else {
                    respMap.put("selfCompanyName", companyInfo.getCompanyName());
                }
            } else {
                respMap.put("selfCompanyName", "");
            }
            if (!StrUtils.isNullOrEmpty(aListData.getProductName())) {
                respMap.put("productName", aListData.getProductName());
            } else {
                respMap.put("productName", "");
            }
            if (aListData.getTaxPrice().compareTo(new BigDecimal(0)) > 0) {
                respMap.put("taxPrice", aListData.getTaxPrice());
            } else {
                respMap.put("taxPrice", 0);
            }
            if (aListData.getSumPrice().compareTo(new BigDecimal(0)) > 0) {
                respMap.put("sumPrice", aListData.getSumPrice());
            } else {
                respMap.put("sumPrice", 0);
            }

            if (aListData.getTaxSumPrice().compareTo(new BigDecimal(0)) > 0) {
                respMap.put("taxSumPrice", aListData.getTaxSumPrice());
            } else {
                respMap.put("taxSumPrice", 0);
            }
            if (!StrUtils.isNullOrEmpty(aListData.getSouceNo())) {
                respMap.put("souceNo", aListData.getSouceNo());
            } else {
                respMap.put("souceNo", "");
            }
            if (!StrUtils.isNullOrEmpty(aListData.getSouceCode())) {
                respMap.put("souceCode", aListData.getSouceCode());
            } else {
                respMap.put("souceCode", "");
            }
            if (!StrUtils.isNullOrEmpty(aListData.getNoticeNo())) {
                respMap.put("noticeNo", aListData.getNoticeNo());
            } else {
                respMap.put("noticeNo", "");
            }
            if (!StrUtils.isNullOrEmpty(aListData.getDrawer())) {
                respMap.put("drawer", aListData.getDrawer());
            } else {
                respMap.put("drawer", "");
            }
            if (!StrUtils.isNullOrEmpty(DateUtils.DateFormatString2(aListData.getOpenDate()))) {
                respMap.put("openDate", DateUtils.DateFormatString2(aListData.getOpenDate()));
            } else {
                respMap.put("openDate", "");
            }
            if (!StrUtils.isNullOrEmpty(aListData.getCancelMan())) {
                respMap.put("cancelDate", aListData.getCancelMan());
            } else {
                respMap.put("cancelDate", "");
            }
            if (!StrUtils.isNullOrEmpty(aListData.getCustomerCompany())) {
                respMap.put("customerNo", aListData.getCustomerNo());
            } else {
                respMap.put("customerNo", "");
            }
            respMap.put("listId", aListData.getListId());
            mapList.add(respMap);
        }
        try {
            ExcelUtils.write(ExcelUtils.generateListContent(mapList, "導出發票結果"), "導出發票結果", response);
        } catch (IOException e) {
            logger.info("########################導出發票數據異常##########################," + e);
            throw new MyException("導出發票結果異常");
        }
        return JsonResult.buildSuccess(new ArrayList<String>());
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章