poi實現excel的導入導出功能

Java使用poi實現excel的導入導出功能:html

工具類ExcelUtil,用於解析和初始化excel的數據:代碼以下java

package com.raycloud.kmmp.item.service.util;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yuanshi.fu
 * @description: excel操做工具類
 * @date 2018/5/23 下午1:52
 */
public class ExcelUtil {

    /**
     * 日誌
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUtil.class);

    /**
     * 總行數
     */
    private static int totalRows = 0;

    /**
     * 總列數
     */
    private static int totalCells = 0;

    /**
     * 無參構造方法
     */
    public ExcelUtil() {
    }

    public static int getTotalRows() {
        return totalRows;
    }

    public static int getTotalCells() {
        return totalCells;
    }

    /**
     * @param is 輸入流
     * @return List<List   <   String>>
     * @throws
     * @description: 導入excel數據
     * @author yuanshi.fu
     * @date 2018/5/23 下午1:56
     */
    public static List<List<String>> importExcel(InputStream is) {

        //定義excel工做薄
        Workbook wb = null;
        try {
            //建立excel工做薄
            wb = WorkbookFactory.create(is);
        } catch (IOException | InvalidFormatException e) {
            LOGGER.error("[" + ExcelUtil.class.getName() + "] importExcel e ", e);
        }
        List<List<String>> dataList = readData(wb);
        return dataList;
    }

    /**
     * @param wb excel工做薄
     * @return List<List   <   String>>
     * @throws
     * @description: 讀取excel數據
     * @author yuanshi.fu
     * @date 2018/5/23 下午2:07
     */
    public static List<List<String>> readData(Workbook wb) {
        List<List<String>> dataLst = new ArrayList<List<String>>();
        if (null == wb) {
            LOGGER.warn("[" + ExcelUtil.class.getName() + "] readData wb is null");
            return Collections.EMPTY_LIST;
        }
        //獲取第一個sheet
        Sheet sheet = wb.getSheetAt(0);
        //獲取excel的行數
        totalRows = sheet.getPhysicalNumberOfRows();

        if (totalRows >= 1 && null != sheet.getRow(0)) {
            totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }

        //循環excel的行
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (null == row) {
                continue;
            }

            //循環excel的列
            List<String> rowLst = new ArrayList<String>();
            for (int c = 0; c < totalCells; c++) {
                Cell cell = row.getCell(c);
                String cellValue = getCellValue(cell);
                rowLst.add(cellValue);
            }
            //保存第r行的數據
            dataLst.add(rowLst);
        }

        return dataLst;
    }

    /**
     * @param is 輸入流
     * @return Map<String   ,       ItemDTO>
     * @throws
     * @description: 導入excel數據
     * @author yuanshi.fu
     * @date 2018/5/23 下午1:56
     */
    public static Map<String, ItemDTO> importExcelData(InputStream is) {

        //定義excel工做薄
        Workbook wb = null;
        try {
            //建立excel工做薄
            wb = WorkbookFactory.create(is);
        } catch (IOException | InvalidFormatException e) {
            LOGGER.error("[" + ExcelUtil.class.getName() + "] importExcelData e ", e);
        }
        Map<String, ItemDTO> dataList = readExcel2ItemDTO(wb);
        return dataList;
    }

    /**
     * @param wb excel工做薄
     * @return Map<String   ,       ItemDTO>
     * @throws
     * @description: 讀取excel數據並轉換爲ItemDTO
     * @author yuanshi.fu
     * @date 2018/5/23 下午2:07
     */
    public static Map<String, ItemDTO> readExcel2ItemDTO(Workbook wb) {

        Map<String, ItemDTO> dataMap = new HashMap<String, ItemDTO>();
        if (null == wb) {
            LOGGER.warn("[" + ExcelUtil.class.getName() + "] readExcel wb is null");
            return dataMap;
        }
        //獲取第一個sheet
        Sheet sheet = wb.getSheetAt(0);
        //獲取excel的行數
        totalRows = sheet.getPhysicalNumberOfRows();

        //循環excel的行
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (null == row) {
                continue;
            }

            //excel的每行內容
            String title = getCellValue(row.getCell(0));
            String price = getCellValue(row.getCell(1));
            //商品庫存數量
            String num = getCellValue(row.getCell(2));
            //商品編號
            String outerId = getCellValue(row.getCell(3));
            // 商品圖片數據,封裝成itemImageDTOList
            String mainImageUrl = getCellValue(row.getCell(4));
            String imageUrl2 = getCellValue(row.getCell(5));
            String imageUrl3 = getCellValue(row.getCell(6));
            String imageUrl4 = getCellValue(row.getCell(7));
            String imageUrl5 = getCellValue(row.getCell(8));
            //相同的商品id的詳情只取一個,需進行保存生成id
            String itemDes = getCellValue(row.getCell(9));
            //sku 封裝成skuDTOList
            String hasSku = getCellValue(row.getCell(10));
            String firstSkuP = getCellValue(row.getCell(11));
            String secondSkuP = getCellValue(row.getCell(12));
            String thirdSkuP = getCellValue(row.getCell(13));
            String firstSkuV = getCellValue(row.getCell(14));
            String secondSkuV = getCellValue(row.getCell(15));
            String thirdSkuV = getCellValue(row.getCell(16));
            String skuPrise = getCellValue(row.getCell(17));
            String skuQuantity = getCellValue(row.getCell(18));

            //商品圖片信息
            List<String> imageUrls = new ArrayList<String>(5);
            if (StringUtils.isNotEmpty(mainImageUrl)) {
                imageUrls.add(mainImageUrl);
            }
            if (StringUtils.isNotEmpty(imageUrl2)) {
                imageUrls.add(imageUrl2);
            }
            if (StringUtils.isNotEmpty(imageUrl3)) {
                imageUrls.add(imageUrl3);
            }
            if (StringUtils.isNotEmpty(imageUrl4)) {
                imageUrls.add(imageUrl4);
            }
            if (StringUtils.isNotEmpty(imageUrl5)) {
                imageUrls.add(imageUrl5);
            }

            //sku屬性值
            List<String> skuPropValue = new ArrayList<String>(3);
            if (StringUtils.isNotEmpty(firstSkuP)) {
                StringBuffer propValueSB = new StringBuffer(3);
                propValueSB.append(firstSkuP).append(":").append(firstSkuV);
                skuPropValue.add(propValueSB.toString());
            }
            if (StringUtils.isNotEmpty(secondSkuP)) {
                StringBuffer propValueSB = new StringBuffer(3);
                propValueSB.append(secondSkuP).append(":").append(secondSkuV);
                skuPropValue.add(propValueSB.toString());
            }
            if (StringUtils.isNotEmpty(thirdSkuP)) {
                StringBuffer propValueSB = new StringBuffer(3);
                propValueSB.append(thirdSkuP).append(":").append(thirdSkuV);
                skuPropValue.add(propValueSB.toString());
            }

            //處理同同樣商品
            if (dataMap.containsKey(outerId)) {
                //獲取
                ItemDTO itemDTO = dataMap.get(outerId);
                List<SkuDTO> skuDTOList = itemDTO.getSkuDTOList();
                if (CollectionUtils.isNotEmpty(skuDTOList)) {
                    //封裝sku
                    SkuDTO skuDTO = new SkuDTO();
                    skuDTO.setCostPrice(new BigDecimal(0));
                    skuDTO.setOuterId(outerId);
                    skuDTO.setPrice(StringUtils.isEmpty(skuPrise) ? null : new BigDecimal(skuPrise));

                    skuDTO.setProperties("");
                    skuDTO.setPropertiesName(StringUtils.join(skuPropValue, ";"));
                    skuDTO.setQuantity(StringUtils.isEmpty(skuPrise) ? null : Long.valueOf(skuQuantity));
                    skuDTOList.add(skuDTO);
                    itemDTO.setSkuDTOList(skuDTOList);
                }
                //保存
                dataMap.put(outerId, itemDTO);
            } else {
                //封裝ItemDTO
                ItemDTO itemDTO = new ItemDTO();
                //商品目錄
                itemDTO.setCategoryId(-1L);
                //商品銷量
                itemDTO.setCustomVolume(0L);
                itemDTO.setTitle(StringUtils.trimToEmpty(title));
                if (StringUtils.isNotEmpty(hasSku) && StringUtils.equals("是", hasSku) && CollectionUtils.isNotEmpty(skuPropValue)) {
                    //sku數據
                    List<SkuDTO> skuDTOList = new ArrayList<SkuDTO>(3);
                    //封裝sku
                    SkuDTO skuDTO = new SkuDTO();
                    skuDTO.setCostPrice(new BigDecimal(0));
                    skuDTO.setOuterId(outerId);
                    skuDTO.setPrice(StringUtils.isEmpty(skuPrise) ? null : new BigDecimal(skuPrise));
                    skuDTO.setProperties("");
                    skuDTO.setPropertiesName(StringUtils.join(skuPropValue, ";"));
                    skuDTO.setQuantity(StringUtils.isEmpty(skuPrise) ? null : Long.valueOf(skuQuantity));
                    skuDTOList.add(skuDTO);
                    itemDTO.setSkuDTOList(skuDTOList);
                }

                if (CollectionUtils.isNotEmpty(itemDTO.getSkuDTOList())) {
                    itemDTO.setHasSku(1);
                    itemDTO.setPrice(new BigDecimal(0));
                } else {
                    itemDTO.setHasSku(0);
                    itemDTO.setPrice(StringUtils.isEmpty(price) ? null : new BigDecimal(price));
                }
                itemDTO.setNum(StringUtils.isEmpty(num) ? 0 : Long.valueOf(num));
                itemDTO.setOuterId(StringUtils.trimToEmpty(outerId));
                itemDTO.setMainImageId(0L);
                itemDTO.setMainImageUrl(mainImageUrl);
                List<ItemImageDTO> itemImageDTOList = new ArrayList<ItemImageDTO>(5);

                for (int i = 0; i < imageUrls.size(); i++) {
                    ItemImageDTO itemImageDTO = new ItemImageDTO();
                    itemImageDTO.setImageId(0L);
                    itemImageDTO.setImageUrl(imageUrls.get(i));
                    itemImageDTOList.add(itemImageDTO);
                }
                itemDTO.setItemImageDTOList(itemImageDTOList);
                //商品描述
                itemDTO.setDescription(itemDes);
                itemDTO.setOriginPrice(new BigDecimal(0));
                itemDTO.setSellerCategoryId("-1");
                itemDTO.setSortId(0L);
                itemDTO.setStatus(1);
                itemDTO.setSubStock(1);

                //保存當前的商品信息
                dataMap.put(outerId, itemDTO);
            }
        }
        return dataMap;
    }

    /**
     * @param cell excel單元
     * @return String
     * @throws
     * @description: 根據excel單元數據類型獲取內容
     * @author yuanshi.fu
     * @date 2018/5/23 下午2:27
     */
    public static String getCellValue(Cell cell) {
        String cellValue = "";
        if (null != cell) {
            // 如下是判斷數據的類型
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC: // 數字
                    if (DateUtil.isCellDateFormatted(cell)) {
                        Date theDate = cell.getDateCellValue();
                        //todo 時間格式可修改
                        SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");
                        cellValue = dff.format(theDate);
                    } else {
                        DecimalFormat df = new DecimalFormat("0");
                        cellValue = df.format(cell.getNumericCellValue());
                    }
                    break;
                case HSSFCell.CELL_TYPE_STRING: // 字符串
                    cellValue = cell.getStringCellValue();
                    break;

                case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                    cellValue = cell.getBooleanCellValue() + "";
                    break;

                case HSSFCell.CELL_TYPE_FORMULA: // 公式
                    cellValue = cell.getCellFormula() + "";
                    break;

                case HSSFCell.CELL_TYPE_BLANK: // 空值
                    cellValue = "";
                    break;

                case HSSFCell.CELL_TYPE_ERROR: // 故障
                    cellValue = "非法字符";
                    break;

                default:
                    cellValue = "未知類型";
                    break;
            }

        }
        return cellValue;
    }

    /**
     * @param
     * @return
     * @throws
     * @description: 導出excel表格數據
     * @author yuanshi.fu
     * @date 2018/5/28 下午5:17
     */
    public static void exportExcel(String title, String[] rowName, List<Object[]> dataList, OutputStream os) {
        try {
            //建立工做薄對象
            HSSFWorkbook workbook = new HSSFWorkbook();
            //建立工做表
            HSSFSheet sheet = workbook.createSheet(title);
            //產生表格標題行
//            HSSFRow rowm = sheet.createRow(0);
//            HSSFCell cellTitle = rowm.createCell(0);

            //sheet樣式定義【getColumnTopStyle()/getStyle()均爲自定義方法 - 在下面  - 可擴展】
            //獲取列頭樣式對象
            HSSFCellStyle columnTopStyle = getColumnTopStyle(workbook);
            //單元格樣式對象
            HSSFCellStyle style = getStyle(workbook);

            //設置標題列的單元格數
//            sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
//            cellTitle.setCellStyle(columnTopStyle);
//            cellTitle.setCellValue(title);

            //定義所需列數
            int columnNum = rowName.length;
            // 在索引0的位置建立行(最頂端的行開始的第二行)
            HSSFRow hssfRow = sheet.createRow(0);

            for (int n = 0; n < columnNum; n++) {
                //建立列頭對應個數的單元格
                HSSFCell hssfCell = hssfRow.createCell(n);
                //設置列頭單元格的數據類型
                hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
                HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
                //設置列頭單元格的值
                hssfCell.setCellValue(text);
                //設置列頭單元格的樣式
                hssfCell.setCellStyle(style);
            }

            for (int i = 0; i < dataList.size(); i++) {
                //填充數據
                Object[] obj = dataList.get(i);
                //建立所在的行數
                HSSFRow row = sheet.createRow(i + 1);

                for (int j = 0; j < obj.length; j++) {
                    HSSFCell cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);
                    if (obj[j] != null && StringUtils.isNotEmpty(obj[j].toString())) {
                        //設置單元格的值
                        cell.setCellValue(obj[j].toString());
                    } else {
                        cell.setCellValue("");
                    }
                    //設置單元格格式
                    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);
                        String cellValue = currentCell.getStringCellValue();
                        if (StringUtils.isNotEmpty(cellValue)
                         && currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                            int length = cellValue.getBytes().length;
                            if (columnWidth < length) {
                                columnWidth = length;
                            }
                        }
                    }
                }
                if(colNum == 0){
                    sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
                }else{
                    sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
                }
            }

            //讓列寬隨着導出的列長自動適應
            workbook.write(os);
        } catch (Exception e) {
            LOGGER.error("[" + ExcelUtil.class.getName() + "] excel導出失敗,", e);
            throw new KmmpException("excel導出失敗!");
        }
    }

    /*
     * 列頭單元格樣式
     */
    public static HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

        // 設置字體
        HSSFFont font = workbook.createFont();
        //設置字體大小
        font.setFontHeightInPoints((short) 16);
        //字體加粗
        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;

    }

    /*
     * 列數據信息單元格樣式
     */
    public static HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 設置字體
        HSSFFont font = workbook.createFont();
        //設置字體大小
        //font.setFontHeightInPoints((short)10);
        //字體加粗
        //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;

    }
}

 

導出僞代碼:c++

//HttpServletResponse設置
String fileName = simpleDateFormat.format(new Date()) + ".xls";
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" +
                new String(fileName.getBytes(), "utf-8"));
        //列數
        String[] columnNames = new String[]{"成交時間","訂單編號","訂單狀態","物流方式","訂單商品總金額","訂單運費","訂單總金額",
                "賣家微信暱稱","收貨人","聯繫電話","收貨地址","物流公司","物流單號","商品名稱","商品編碼","SKU信息","商品單價","購買數量"};
//封裝數據
...dataList
//調用
ExcelUtil.exportExcel(fileName, columnNames, dataList, response.getOutputStream());           

導入功能主要是將excel的數據解析出來,以後作本身的業務處理,即ExcelUtil.importExcelData方法apache

 

參照:微信

http://www.javashuo.com/article/p-mhrdjczv-bo.htmlapp

http://www.javashuo.com/article/p-aludsbdx-n.html工具

http://www.javashuo.com/article/p-fjlqvxod-a.html字體

相關文章
相關標籤/搜索