POI導入

controller:

mezura-sa AreaController
   /**
     * 地域模板文件下載
     * @param response
     */
    @GetMapping(BranchUrl.AREA_DOWNLOAD_TEMPLATE)
    public void download(HttpServletResponse response){
        FileUtils.downLoadFile(response, sysConfig.getFilePath(), sysConfig.getAreaTemplate());
    }

    /**
     * 導入地域信息 省市
     */
    @RequestMapping(BranchUrl.AREA_BATCH_IMPORT)
    @ResponseBody
    public PageData importArea(@RequestParam("shortUrl") String shortUrl, @RequestParam("countryId") Integer countryId) throws IOException {
        File file = new File(sysConfig.getFilePath().concat(shortUrl));
        if(!file.exists()){
            return PageData.getInstanceOfError(ConstTipCode.FAIL_FILE_NOT_FOUND, "文件不存在");
        }
        //讀取excel文件內容
        String fileName = file.getName();
        InputStream inputStream = new FileInputStream(file);
        Workbook workbook = null;
        if(ExportExcelUtils.isExcel2003(fileName)){
            workbook = new HSSFWorkbook(inputStream);
        }else if(ExportExcelUtils.isExcel2007(fileName)){
            workbook = new XSSFWorkbook(inputStream);
        }else{
            return PageData.getInstanceOfError(ConstTipCode.FAIL_FORMAT_INCORRECT, "文件格式不正確");
        }
        Sheet sheet = workbook.getSheetAt(0);

        //封裝excel數據到map對象
        ArrayListMultimap<String, String> provinceCityMultimap = ArrayListMultimap.create();
        for(int i = 1; i <= sheet.getLastRowNum(); i++){
            Row row = sheet.getRow(i);
            String provinceName = row.getCell(0).getStringCellValue().trim();
            String cityName = row.getCell(1).getStringCellValue().trim();
            provinceCityMultimap.put(provinceName, cityName);
        }
        //插入數據庫
        provinceService.batchAddProvinceAndCity(provinceCityMultimap, countryId);
        return PageData.getInstanceOfSuccess(ConstTipCode.SUCCESS_OPERATE);
    }

依賴的工具類:ExportExcelUtils 

package com.mezura.core.utils;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;

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

/**
 * Created by zouLu on 2017-12-14.
 */
public class ExportExcelUtils {

    public static void exportExcel(HttpServletResponse response, String fileName, ExcelData data) throws Exception {
        // 告訴瀏覽器用什麼軟件可以打開此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下載文件的默認名稱
        response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
        exportExcel(data, response.getOutputStream());
    }

    public static void exportExcel(ExcelData data, OutputStream out) throws Exception {

        HSSFWorkbook wb = new HSSFWorkbook();
        try {
            String sheetName = data.getName();
            if (null == sheetName) {
                sheetName = "Sheet1";
            }
            HSSFSheet sheet = wb.createSheet(sheetName);
            writeExcel(wb, sheet, data);

            wb.write(out);
        } finally {

        }
    }

    private static void writeExcel(HSSFWorkbook wb, Sheet sheet, ExcelData data) {

        int rowIndex = 0;

        rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles());
        writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
        autoSizeColumns(sheet, data.getTitles().size() + 1);

    }

    private static int writeTitlesToExcel(HSSFWorkbook wb, Sheet sheet, List<String> titles) {
        int rowIndex = 0;
        int colIndex = 0;

        Font titleFont = wb.createFont();
        titleFont.setFontName("simsun");
        // titleFont.setFontHeightInPoints((short) 14);
        titleFont.setColor(IndexedColors.BLACK.index);

        HSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        titleStyle.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
        titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        titleStyle.setFont(titleFont);
        setBorder(titleStyle, (short) 1, HSSFColor.BLACK.index);

        Row titleRow = sheet.createRow(rowIndex);
        // titleRow.setHeightInPoints(25);
        colIndex = 0;

        for (String field : titles) {
            Cell cell = titleRow.createCell(colIndex);
            cell.setCellValue(field);
            cell.setCellStyle(titleStyle);
            colIndex++;
        }

        rowIndex++;
        return rowIndex;
    }

    private static int writeRowsToExcel(HSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) {
        int colIndex = 0;

        Font dataFont = wb.createFont();
        dataFont.setFontName("simsun");
        // dataFont.setFontHeightInPoints((short) 14);
        dataFont.setColor(IndexedColors.BLACK.index);

        HSSFCellStyle dataStyle = wb.createCellStyle();
        dataStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        dataStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        dataStyle.setFont(dataFont);
        setBorder(dataStyle, (short) 1, HSSFColor.BLACK.index);

        for (List<Object> rowData : rows) {
            Row dataRow = sheet.createRow(rowIndex);
            // dataRow.setHeightInPoints(25);
            colIndex = 0;

            for (Object cellData : rowData) {
                Cell cell = dataRow.createCell(colIndex);
                if (cellData != null) {
                    cell.setCellValue(cellData.toString());
                } else {
                    cell.setCellValue("");
                }

                cell.setCellStyle(dataStyle);
                colIndex++;
            }
            rowIndex++;
        }
        return rowIndex;
    }

    private static void autoSizeColumns(Sheet sheet, int columnNumber) {

        for (int i = 0; i < columnNumber; i++) {
            int orgWidth = sheet.getColumnWidth(i);
            sheet.autoSizeColumn(i, true);
            int newWidth = (int) (sheet.getColumnWidth(i) + 100);
            if (newWidth > orgWidth) {
                sheet.setColumnWidth(i, newWidth);
            } else {
                sheet.setColumnWidth(i, orgWidth);
            }
        }
    }

    private static void setBorder(HSSFCellStyle style, Short border, Short color) {
        style.setBorderTop(border);
        style.setBorderLeft(border);
        style.setBorderRight(border);
        style.setBorderBottom(border);
        style.setTopBorderColor(color);
        style.setLeftBorderColor(color);
        style.setRightBorderColor(color);
        style.setBottomBorderColor(color);
    }

    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }
}

 

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