其他分享
首页 > 其他分享> > Excel工具类

Excel工具类

作者:互联网

添加依赖:

<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>4.1.2</version>
</dependency>

<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>4.1.2</version>
</dependency>

1)创建Excel并写数据

import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.util.*;

/**
 * 创建Excel并写数据
 */
public final class ExcelWriteUtil {

    /**
     * 2003以下版本的excel
     */
    public static final String EXCEL_2003L = ".xls";
    /**
     * 2007以上版本的excel
     */
    public static final String EXCEL_2007U = ".xlsx";

    /**
     * 创建Excel Workbook
     *
     * @param type
     */
    public static Workbook createWorkbook(String type) {
        Workbook wb = null;
        if (EXCEL_2003L.equals(type)) {
            wb = new HSSFWorkbook(); // 定义一个新的工作簿
        } else {
            wb = new XSSFWorkbook();
        }
        return wb;
    }

    /**
     * 创建Excel Sheet
     *
     * @param workbook Excel Workbook
     * @param name     sheet的名称
     * @return
     */
    public static Sheet createSheet(Workbook workbook, String name) {
        return workbook.createSheet(name);  // 创建一个Sheet页
    }

    /**
     * 为一个Sheet创建列头
     *
     * @param sheet       sheet实例
     * @param rowNum      行号(从0开始)
     * @param nameHeaders 列头, 如:姓名、年龄等(或者name、age等)
     */
    public static Row createSheetHeaderRow(Workbook workbook, Sheet sheet, int rowNum, List<String> nameHeaders) {
        Row row = sheet.createRow(rowNum);
        CellStyle cellStyle = getHeaderCellStyle(workbook);
        setDefaultRowHeight(row);
        for (int i = 0; i < nameHeaders.size(); i++) {
            Cell cell = createRowCell(row, i, nameHeaders.get(i));
            setDefaultColumnWidth(sheet, i);
            cell.setCellStyle(cellStyle);
        }
        return row;
    }

    /**
     * 填充数据行
     *
     * @param workbook
     * @param sheet
     * @param headRow      列头行
     * @param startRow     正文数据的开始行(从0开始)
     * @param rowValueList 数据(不宜过多)
     */
    public static void fillRowData(Workbook workbook, Sheet sheet, Row headRow, int startRow, List<Map<String, Object>> rowValueList) {
        int start = headRow.getFirstCellNum();
        int end = headRow.getLastCellNum();
        Map<String, Integer> cellIndexMap = new HashMap();
        for (int i = start; i < end; i++) {
            //存储列头与cell index的关系
            cellIndexMap.put(headRow.getCell(i).getStringCellValue(), i);
        }
        CellStyle cellStyle = getCellStyle(workbook);
        //填充数据
        for (int i = 0; i < rowValueList.size(); i++) {
            Row row = sheet.createRow(i + startRow);
            setDefaultRowHeight(row);
            Map<String, Object> rowValue = rowValueList.get(i);
            Set<Map.Entry<String, Object>> entries = rowValue.entrySet();
            Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                int cellIndex = cellIndexMap.get(entry.getKey());
                Cell cell = createRowCell(row, cellIndex, entry.getValue());
                cell.setCellStyle(cellStyle);
            }
        }
    }

    /**
     * 创建单元格
     *
     * @param row         所在行实例
     * @param columnIndex 列索引
     * @param value       单元格值
     * @return
     */
    public static Cell createRowCell(Row row, int columnIndex, Object value) {
        Cell cell = row.createCell(columnIndex);  // 创建单元格
        if (value == null) {
            value = "";
        }
        if (row instanceof HSSFRow) {
            cell.setCellValue(new HSSFRichTextString(String.valueOf(value)));
        } else {
            cell.setCellValue(new XSSFRichTextString(String.valueOf(value)));
        }
        return cell;
    }

    /**
     * 正文的单元格设置
     *
     * @param workbook
     * @return
     */
    public static CellStyle getCellStyle(Workbook workbook) {
        // 创建单元格样式
        CellStyle cellStyle = workbook.createCellStyle();
        // 设置单元格水平方向对其方式
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        // 设置单元格垂直方向对其方式
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置字体
        cellStyle.setFont(getFontStyle(workbook));
        return cellStyle;
    }

    /**
     * 列头的单元格设置
     *
     * @param workbook
     * @return
     */
    public static CellStyle getHeaderCellStyle(Workbook workbook) {
        // 创建单元格样式
        CellStyle cellStyle = workbook.createCellStyle();
        // 设置单元格水平方向对其方式
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        // 设置单元格垂直方向对其方式
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置字体
        cellStyle.setFont(getHeaderFontStyle(workbook));
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
        cellStyle.setBorderTop(BorderStyle.THIN);//上边框
        cellStyle.setBorderRight(BorderStyle.THIN);//右边框
        return cellStyle;
    }

    /**
     * 正文的字体设置
     *
     * @param workbook
     * @return
     */
    public static Font getFontStyle(Workbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("黑体");
        font.setColor(IndexedColors.BLACK.getIndex());
        font.setFontHeightInPoints((short) 10);//设置字体大小
        return font;
    }

    /**
     * 列头的字体设置
     *
     * @param workbook
     * @return
     */
    public static Font getHeaderFontStyle(Workbook workbook) {
        Font font = workbook.createFont();
        font.setColor(IndexedColors.RED.getIndex());
        font.setFontName("黑体");
        font.setFontHeightInPoints((short) 10);//设置字体大小
        font.setBold(true);
        return font;
    }

    /**
     * 设置默认的行高
     *
     * @param row
     */
    public static void setDefaultRowHeight(Row row) {
        row.setHeight((short) (20 * 20));
    }

    /**
     * 设置默认的列宽
     *
     * @param sheet
     * @param columnIndex
     */
    public static void setDefaultColumnWidth(Sheet sheet, int columnIndex) {
        sheet.setColumnWidth(columnIndex, 20 * 256);
    }
}

2)解析excel读取数据

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 解析excel工具类
 */
public final class ExcelReadUtil {

    private ExcelReadUtil() {
    }

    /**
     * 2003以下版本的excel
     */
    public static final String EXCEL_2003L = ".xls";
    /**
     * 2007以上版本的excel
     */
    public static final String EXCEL_2007U = ".xlsx";

    public static final String DATA_GENERAL_FORMAT = "General";

    public static final ThreadLocal<DecimalFormat> DECIMAL_FORMAT_LOCAL = ThreadLocal.withInitial(() -> new DecimalFormat("0"));

    public static final ThreadLocal<DecimalFormat> DECIMAL_FORMAT_LOCAL2 = ThreadLocal.withInitial(() -> new DecimalFormat("0.00"));

    /**
     * 获取IO流中的数据,组装成List<Object[]>对象
     *
     * @param sheet    第几张工作簿(以0开始)
     * @param startRow 工作簿中第行开始(以0开始)
     * @return
     * @throws Exception
     */
    public static List<Object[]> getExcelData(Sheet sheet, int startRow) throws Exception {
        List<Object[]> list = new ArrayList();
        //遍历当前sheet中的所有行
        List<Object> tampList = null;
        Row row = null;
        Cell cell = null;
        for (int i = startRow; i <= sheet.getLastRowNum(); i++) {
            row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            //遍历所有的列
            tampList = new ArrayList();
            for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
                cell = row.getCell(j);
                tampList.add(getCellValue(cell));
            }
            list.add(tampList.toArray());
        }
        return list;
    }

    /**
     * 获取指定某一行的数据
     *
     * @param sheet
     * @param rowIndex 工作簿中第行开始(以0开始)
     * @return
     */
    public static List<Object> getRowData(Sheet sheet, int rowIndex) {
        List<Object> list = new ArrayList();
        Row row = sheet.getRow(rowIndex);
        if (row == null) {
            return list;
        }
        Cell cell = null;
        for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
            cell = row.getCell(i);
            list.add(getCellValue(cell));
        }
        return list;
    }

    /**
     * 获取excel数据, 每一行数据就是一个Map, key为字段, value为数据值
     *
     * @return
     */
    public static List<Map<String, Object>> getExcelDataMapList(Sheet sheet, int startDataRowIndex, int headerRowIndex) throws Exception {
        //获取列头
        List<Object> headerCols = getRowData(sheet, headerRowIndex);
        //开始解析实际数据
        Row row = null;
        Cell cell = null;
        List<Map<String, Object>> list = new ArrayList();
        //遍历当前sheet中的所有行
        for (int i = startDataRowIndex; i <= sheet.getLastRowNum(); i++) {
            row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            Map<String, Object> rowMap = new HashMap(16);
            for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
                cell = row.getCell(j);
                rowMap.put(String.valueOf(headerCols.get(j)), getCellValue(cell));
            }
            if (rowMap.isEmpty()) {
                continue;
            }
            list.add(rowMap);
        }
        return list;
    }

    /**
     * 描述:根据文件后缀,自适应上传文件的版本
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static Workbook getWorkbook(File file) throws Exception {
        return getWorkbook(new FileInputStream(file), file.getName());
    }

    /**
     * 描述:根据文件后缀,自适应上传文件的版本
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static Workbook getWorkbook(MultipartFile file) throws Exception {
        return getWorkbook(file.getInputStream(), file.getOriginalFilename());
    }

    /**
     * 获取sheet
     *
     * @param workbook
     * @param index    第几张工作簿(以0开始)
     * @return
     */
    public static Sheet getExcelSheet(Workbook workbook, int index) {
        Sheet sheet = workbook.getSheetAt(index);
        if (sheet == null) {
            throw new RuntimeException("Excel工作薄为空!");
        }
        return sheet;
    }

    /**
     * 获取Sheet的最大行数
     *
     * @return
     */
    public static int getSheetMaxRowNum(Sheet sheet) {
        return sheet.getLastRowNum() - sheet.getFirstRowNum() + 1;
    }

    public static Workbook getWorkbook(InputStream in, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (EXCEL_2003L.equals(fileType)) {
            //2003以下
            wb = new HSSFWorkbook(in);
        } else if (EXCEL_2007U.equals(fileType)) {
            //2007以上
            wb = new XSSFWorkbook(in);
        } else {
            throw new RuntimeException("文件解析错误!");
        }
        if (null == wb) {
            throw new RuntimeException("Excel为空!");
        }
        return wb;
    }

    /**
     * 描述:对表格中数值进行格式化
     *
     * @param cell
     * @return
     */
    public static Object getCellValue(Cell cell) {
        //用String接收所有返回的值
        String value = null;
        switch (cell.getCellType()) {
            case STRING:
                //String类型的数据
                value = cell.getStringCellValue();
                break;

            case NUMERIC:
                //数值类型(取值用cell.getNumericCellValue() 或cell.getDateCellValue())
                if (DATA_GENERAL_FORMAT.equals(cell.getCellStyle().getDataFormatString())) {
                    value = DECIMAL_FORMAT_LOCAL.get().format(cell.getNumericCellValue());
                } else if (DateUtil.isCellDateFormatted(cell)) {
                    value = DECIMAL_FORMAT_LOCAL.get().format(DateUtil.getJavaDate(cell.getNumericCellValue()));
                } else {
                    value = DECIMAL_FORMAT_LOCAL2.get().format(cell.getNumericCellValue());
                }
                break;

            case BOOLEAN:
                //Boolean类型
                value = String.valueOf(cell.getBooleanCellValue());
                break;
            case FORMULA:
                //表达式类型
                value = String.valueOf(cell.getCellFormula());
                break;

            case ERROR:
                value = String.valueOf(cell.getErrorCellValue());
                break;
            default:
                value = "";
                break;
        }
        if (value == null) {
            value = "";
        }
        if (cell == null) {
            return "";
        }
        return value;
    }
}

3)测试

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * controller测试
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {

    private static final List<String> ENG_NAME_LIST = Arrays.asList("prodCode", "prodName", "prodPrice", "prodAddr");
    private static final List<String> CIN_NAME_LIST = Arrays.asList("产品编码", "产品名称", "价格", "产地");
    private static List<Map<String, String>> nameHeaderMapList = new ArrayList();

    static {
        for (int i = 0; i < ENG_NAME_LIST.size(); i++) {
            HashMap map = new HashMap();
            map.put(ENG_NAME_LIST.get(i), CIN_NAME_LIST.get(i));
            nameHeaderMapList.add(map);
        }
    }

    private static List<Map<String, Object>> dataList = new ArrayList();

    static {
        Map<String, Object> item1 = new HashMap();
        item1.put("prodCode", "0001");
        item1.put("prodName", "红菩提");
        item1.put("prodPrice", 5.20d);
        item1.put("prodAddr", "广东省广州市");
        dataList.add(item1);
        Map<String, Object> item2 = new HashMap();
        item2.put("prodCode", "10001");
        item2.put("prodName", "黑巨峰");
        item2.put("prodPrice", 15.20d);
        item2.put("prodAddr", "广东省茂名市");
        dataList.add(item2);
    }

    /**
     * 创建excel并保存到硬盘
     * POST http://localhost:9090/changyong/excel/createExcel2003
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("/createExcel2003")
    public String createExcel2003() throws IOException {
        Workbook workbook = ExcelWriteUtil.createWorkbook(ExcelWriteUtil.EXCEL_2003L);
        Sheet sheet = ExcelWriteUtil.createSheet(workbook, "产品列表");
        ExcelWriteUtil.createSheetHeaderRow(workbook, sheet, 0, CIN_NAME_LIST);
        Row engRow = ExcelWriteUtil.createSheetHeaderRow(workbook, sheet, 1, ENG_NAME_LIST);
        ExcelWriteUtil.fillRowData(workbook, sheet, engRow, 2, dataList);

        //目录不存在则创建
        String directoryPath = "D:/javatest/createExcel2003/";
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        String fileName = directoryPath + "excel2003.xls";

        try (FileOutputStream out = new FileOutputStream(fileName)) {
            workbook.write(out);
        }
        return "success";
    }

    /**
     * 读取excel 2003数据
     * POST http://localhost:9090/changyong/excel/readExcel2003
     * form-data 选中要解析的excel文件
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("/readExcel2003")
    public String readExcel2003(MultipartFile file) throws Exception {
        Workbook workbook = ExcelReadUtil.getWorkbook(file);
        Sheet sheet = ExcelReadUtil.getExcelSheet(workbook, 0);
        List<Map<String, Object>> excelDataMapList = ExcelReadUtil.getExcelDataMapList(sheet, 2, 1);
        System.out.println("读取到的数据为:" + excelDataMapList);
        return "success";
    }
}

 

标签:return,Excel,cell,static,workbook,sheet,工具,public
来源: https://www.cnblogs.com/xfeiyun/p/16362887.html