Java读取excel,导出excel

1.依赖

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

2.代码

**

2.1导入导出工具类

**

import com.common.model.ExcelData;
import com.utils.StringUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ExcelUtil {
    static Logger log = LoggerFactory.getLogger(ExcelUtil.class);

    //读取excel
    public static Workbook readExcel(String filePath) {
        Workbook wb = null;
        if (filePath == null) {
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
                return wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                return wb = new XSSFWorkbook(is);
            } else {
                return wb = null;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    public static Object getCellFormatValue(Cell cell) {
        Object cellValue = null;
        if (cell != null) {
            //判断cell类型
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC: {
                    cellValue = String.valueOf(cell.getNumericCellValue());
                    break;
                }
                case Cell.CELL_TYPE_FORMULA: {
                    //判断cell是否为日期格式
                    if (DateUtil.isCellDateFormatted(cell)) {
                        //转换为日期格式YYYY-mm-dd
                        cellValue = cell.getDateCellValue();
                    } else {
                        //数字
                        cellValue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING: {
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = "";
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }


    /**
     * 方法名:exportExcel
     * 功能:导出Excel
     */
    public static void exportExcel(HttpServletResponse response, ExcelData data) {
        log.info("导出解析开始,fileName:{}", data.getFileName());
        try {
//            response.setHeader("content-Type", "application/vnd.ms-excel;charset=utf8");
//            response.setContentType("application ns.ms-excel");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + URLEncoder.encode(data.getFileName() + ".xlsx", "utf-8"));
            //实例化HSSFWorkbook
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建一个Excel表单,参数为sheet的名字
            HSSFSheet sheet = workbook.createSheet("sheet");
            //设置表头
            setTitle(workbook, sheet, data.getHead());
            //设置单元格并赋值
            setData(sheet, data.getData());
            //设置浏览器下载
            setBrowser(response, workbook, data.getFileName());
            log.info("导出解析成功!");
        } catch (Exception e) {
            log.info("导出解析失败!", e);
        }
    }

    /**
     * 方法名:setTitle
     * 功能:设置表头
     */
    private static void setTitle(HSSFWorkbook workbook, HSSFSheet sheet, String[] str) {
        try {
            HSSFRow row = sheet.createRow(0);
            //设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度
            for (int i = 0; i <= str.length; i++) {
                sheet.setColumnWidth(i, 15 * 256);
            }
            //设置为居中加粗,格式化时间格式
            HSSFCellStyle style = workbook.createCellStyle();
            HSSFFont font = workbook.createFont();
            font.setBold(true);
            style.setFont(font);
            style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
            //创建表头名称
            HSSFCell cell;
            for (int j = 0; j < str.length; j++) {
                cell = row.createCell(j);
                cell.setCellValue(str[j]);
                cell.setCellStyle(style);
            }
        } catch (Exception e) {
            log.info("导出时设置表头失败!", e);
        }
    }

    /**
     * 方法名:setData
     * 功能:表格赋值
     */
    private static void setData(HSSFSheet sheet, List<String[]> data) {
        try {
            int rowNum = 1;
            for (int i = 0; i < data.size(); i++) {
                HSSFRow row = sheet.createRow(rowNum);
                for (int j = 0; j < data.get(i).length; j++) {
                    row.createCell(j).setCellValue(data.get(i)[j]);
                }
                rowNum++;
            }
            log.info("表格赋值成功!");
        } catch (Exception e) {
            log.error("表格赋值失败!", e);
        }
    }

    /**
     * 方法名:setBrowser
     * 功能:使用浏览器下载
     */
    private static void setBrowser(HttpServletResponse response, HSSFWorkbook workbook, String fileName) {
        try {
            //清空response
            response.reset();
            //设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=gb2312");
            //将excel写入到输出流中
            workbook.write(os);
            os.flush();
            os.close();
            log.info("设置浏览器下载成功!");
        } catch (Exception e) {
            log.error("设置浏览器下载失败!", e);
        }

    }

    /**
     * 方法名:exportExcel
     * 功能:导出Excel
     */
    public static void exportExcelSeven(HttpServletResponse response, ExcelData data) {
        log.info("导出解析开始,fileName:{}", data.getFileName());
        try {

            response.setHeader("Content-disposition",
                    "attachment;filename=" + URLEncoder.encode(data.getFileName() + ".xlsx", "utf-8"));
            //实例化HSSFWorkbook
            XSSFWorkbook workbook = new XSSFWorkbook();
            //创建一个Excel表单,参数为sheet的名字
            XSSFSheet sheet = workbook.createSheet("sheet");
            //设置表头
            setTitle(workbook, sheet, data.getHead());
            //设置单元格并赋值
            setData(sheet, data.getData());
            //设置浏览器下载
            setBrowser(response, workbook, data.getFileName());
            log.info("导出解析成功!");
        } catch (Exception e) {
            log.info("导出解析失败!", e);
        }
    }

    /**
     * 设置表头 和上面的一致
     *
     * @param workbook
     * @param sheet
     * @param str
     */
    private static void setTitle(XSSFWorkbook workbook, XSSFSheet sheet, String[] str) {
        try {
            XSSFRow row = sheet.createRow(0);
            //设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度
            for (int i = 0; i <= str.length; i++) {
                sheet.setColumnWidth(i, 15 * 256);
            }
            //设置为居中加粗,格式化时间格式
            XSSFCellStyle style = workbook.createCellStyle();
            XSSFFont font = workbook.createFont();
            font.setBold(true);
            style.setFont(font);
            style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
            //创建表头名称
            XSSFCell cell;
            for (int j = 0; j < str.length; j++) {
                cell = row.createCell(j);
                cell.setCellValue(str[j]);
                cell.setCellStyle(style);
            }
        } catch (Exception e) {
            log.info("导出时设置表头失败!", e);
        }
    }

    /**
     * 充填数据和上面的一致,这个是 2007版的
     *
     * @param sheet
     * @param data
     */
    private static void setData(XSSFSheet sheet, List<String[]> data) {
        try {
            int rowNum = 1;
            for (int i = 0; i < data.size(); i++) {
                XSSFRow row = sheet.createRow(rowNum);
                for (int j = 0; j < data.get(i).length; j++) {
                    row.createCell(j).setCellValue(data.get(i)[j]);
                }
                rowNum++;
            }
            log.info("表格赋值成功!");
        } catch (Exception e) {
            log.info("表格赋值失败!", e);
        }
    }

    /**
     * 下载 2007版
     *
     * @param response
     * @param workbook
     * @param fileName
     */
    private static void setBrowser(HttpServletResponse response, XSSFWorkbook workbook, String fileName) {
        try {
            //清空response
            response.reset();
            //设置response的Header
            response.setHeader("content-type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));

            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            //将excel写入到输出流中
            workbook.write(os);
            os.flush();
            os.close();
            log.info("设置浏览器下载成功!");
        } catch (Exception e) {
            log.info("设置浏览器下载失败!", e);
        }

    }

    public static List<Map<String, String>> readExcel(MultipartFile file) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        //创建工作簿
        Workbook workbook = null;

        try {
            workbook = WorkbookFactory.create(file.getInputStream());

            //获取sheet数量
            int numberOfSheets = workbook.getNumberOfSheets();

            for (int i = 0; i < numberOfSheets; i++) {
                //获取当前工作表
                Sheet sheet = workbook.getSheetAt(i);
                //获取最大行数
                int rownum = sheet.getPhysicalNumberOfRows();

                Row titlerow = sheet.getRow(0);
                int tilcol = titlerow.getPhysicalNumberOfCells();
                String[] columns = new String[tilcol];
                for (int z = 0; z < tilcol; z++) {
                    String cellData = (String) getCellFormatValue(titlerow.getCell(z));
                    columns[z] = cellData;
                }
                for (int j = 1; j < rownum; j++) {
                    Map<String, String> map = new LinkedHashMap<String, String>();
                    Row rowData = sheet.getRow(j);
                    if (rowData != null) {
                        int column = rowData.getPhysicalNumberOfCells();
                        for (int z = 0; z < column; z++) {
                            if (!StringUtil.isEmpty(rowData.getCell(z).getStringCellValue())) {
                                String cellData = (String) getCellFormatValue(rowData.getCell(z));
                                map.put(columns[z], cellData);
                            }
                        }
                    }
                    list.add(map);
                }
            }
        } catch (IOException | InvalidFormatException e) {
            log.error("read excel error ", e);
        }
        return list;
    }

    public static List<Map<String, String>> readExcelData(MultipartFile file) {
        List<Map<String, String>> data = new ArrayList<>();
        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        String cellData = null;
        String[] columns = {"question", "answer", "entity", "relation"};
        try {
            wb = WorkbookFactory.create(file.getInputStream());
            //获取第一个sheet
            sheet = wb.getSheetAt(0);
            //获取最大行数
            int rowNum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
            int column = row.getPhysicalNumberOfCells();
            for (int i = 1; i < rowNum; i++) {
                Map<String, String> map = new LinkedHashMap<>();
                row = sheet.getRow(i);
                if (row != null) {
                    for (int j = 0; j < column; j++) {
                        cellData = (String) getCellFormatValue(row.getCell(j));
                        if (cellData != null) {
                            map.put(columns[j], cellData);
                        }
                    }
                } else {
                    break;
                }
                data.add(map);
            }

        } catch (IOException | InvalidFormatException e) {
            log.error("read excel error ", e);
        }

        return data;
    }


    public static void main(String[] args) {
        //测试导出excel
        String [] header = {"col1", "col2", "col2", "col4"};
        List<String[]> data = new ArrayList<>();
        String[] data1 = {"张三的籍贯是哪里", "江西省", "张三", "籍贯"};
        String[] data2 = {"张三的籍贯是哪里2", "江西省2", "张三2", "籍贯2"};
        data.add(data1);
        data.add(data2);
        ExcelData excelData = new ExcelData("data", header, data);
//ExcelUtil.exportExcel(response, excelData);

        //测试读取excel
        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        List<Map<String, String>> list = null;
        String cellData = null;
        String filePath = "E:\\data.xlsx";

        String columns[] = {"question", "answer", "entity", "relation"};
        wb = readExcel(filePath);
        if (wb != null) {
            //用来存放表中数据
            list = new ArrayList<Map<String, String>>();
            //获取第一个sheet
            sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
            int colnum = row.getPhysicalNumberOfCells();
            for (int i = 1; i < rownum; i++) {
                Map<String, String> map = new LinkedHashMap<String, String>();
                row = sheet.getRow(i);
                if (row != null) {
                    for (int j = 0; j < colnum; j++) {
                        cellData = (String) getCellFormatValue(row.getCell(j));
                        map.put(columns[j], cellData);
                    }
                } else {
                    break;
                }
                list.add(map);
            }
        }
        //遍历解析出来的list
        for (Map<String, String> map : list) {
            for (Entry<String, String> entry : map.entrySet()) {
                System.out.print(entry.getKey() + ":" + entry.getValue() + ",");
            }
            System.out.println();
        }

    }

}

2.2 ExcelData类


import java.util.List;

public class ExcelData {

    String fileName;

    String[] head;

    List<String[]> data;

    public ExcelData() {
    }

    public ExcelData(String fileName, String[] head, List<String[]> data) {
        this.fileName = fileName;
        this.head = head;
        this.data = data;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String[] getHead() {
        return head;
    }

    public void setHead(String[] head) {
        this.head = head;
    }

    public List<String[]> getData() {
        return data;
    }

    public void setData(List<String[]> data) {
        this.data = data;
    }


}

你可能感兴趣的:(java,excel,开发语言)