Maven

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.14</version><!--$NO-MVN-MAN-VER$ -->
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>3.14</version><!--$NO-MVN-MAN-VER$ -->
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.14</version><!--$NO-MVN-MAN-VER$ -->
</dependency>

导入:

package com.pan.test;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ImportExcel {

    public static void main(String[] args) throws Exception {
        ImportExcel importExcel = new ImportExcel();
        FileInputStream inputStream = new FileInputStream("C:\\Users\\prg48\\Desktop\\入选名单表.xls");
        String suffix = "xls";
        int startRow = 0;
        List<String[]> strings = importExcel.paresExcel(inputStream,suffix,startRow);
        strings.stream().forEach(s -> {
            if (s!=null) {
                Arrays.stream(s).forEach(ss -> {
                    if (ss != null) {
                        System.out.print(ss.toString());
                    }
                    System.out.print("   ");
                });
                System.out.println();
            }
        });
    }

    /**
     * 解析文件的方法
     * @param  inputStream
     * @param  suffix
     * @param  startRow
     * @return List<String[]>
    */
    public List<String[]> paresExcel(InputStream inputStream, String suffix, int startRow) throws Exception {
        //1.定义Excel对象变量
        Workbook workbook = null;
        //2.判断后缀 决定解析方式
        if ("xls".equals(suffix)) {
            //2003
            workbook = new HSSFWorkbook(inputStream);
        } else if ("xlsx".equals(suffix)) {
            //2007
            workbook = new XSSFWorkbook(inputStream);
        }else{
            //未知内容
        }
        //判断
        if (workbook == null) {
            return null;
        }
        //获取工作表sheet
        Sheet sheet = workbook.getSheetAt(0);
        if (sheet == null) {
            //空表格
            return null;
        }
        //获取表格最后一行 行号
        int lastRowNum = sheet.getLastRowNum();
        //判断行号
        if (lastRowNum <= startRow) {
            return  null;
        }

        List<String[]> result = new ArrayList<>();

        //定义行变量和单元格变量
        Row row = null;
        Cell cell = null;
        //循环读取
        for (int rowNum = startRow; rowNum < lastRowNum; rowNum++){
            row = sheet.getRow(rowNum);
            //获取当前行的第一列和最后一列的标记
            short firstCellNum = row.getFirstCellNum();
            short lastCellNum = row.getLastCellNum();
            if(lastCellNum!=0){
                String[] rowArray = new String[lastCellNum];
                for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++){
                    cell = row.getCell(cellNum);
                    if (cell == null) {
                        rowArray[cellNum] = null;
                    }else {
                        rowArray[cellNum] = parseCell(cell);
                    }
                }
                result.add(rowArray);
            }
        }
            return result;
    }

    /**
     * 解析单元格字符串
     * @return String
     */
    private String parseCell(Cell cell){
        String cellStr = null;
        switch (cell.getCellType()){
            case XSSFCell.CELL_TYPE_STRING:
                cellStr = cell.getStringCellValue();
                break;
            case XSSFCell.CELL_TYPE_NUMERIC:
                cellStr = cell.getNumericCellValue()+"";
                break;
            case XSSFCell.CELL_TYPE_BLANK:
                cellStr = null;
                break;
            default:
                cellStr = "";
        }
        return cellStr;
    }

}

导出:

package com.pan.test;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

public class ExportExcel {
    public static void main(String[] args) throws Exception {
        ImportExcel importExcel = new ImportExcel();
        FileInputStream inputStream = new FileInputStream("C:\\Users\\prg48\\Desktop\\入选名单表.xls");
        String suffix = "xls";
        int startRow = 0;
        List<String[]> strings = importExcel.paresExcel(inputStream,suffix,startRow);

        ExportExcel exportExcel = new ExportExcel();
        FileOutputStream outputStream = new FileOutputStream("C:\\Users\\prg48\\Desktop\\test.xls");
        exportExcel.exportExcel(strings,outputStream);

    }
    /**
     * 文件导出方法
     * @param resource
     * @param outputStream
     */
    public void exportExcel(List<String[]> resource, OutputStream outputStream) throws Exception {
        //创建Excel对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个表格
        HSSFSheet sheet = workbook.createSheet("sheet1");
        //创建表头
        String[] headerStr = resource.get(0);
        HSSFRow headerRow = sheet.createRow(0);
        for (int i=0; i<headerStr.length; i++) {
            //设置列宽
            sheet.setColumnWidth(i,5000);
        }
        //设置表头单元格样式
        HSSFCellStyle headerStyle = workbook.createCellStyle();
        //水平居中
        headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //设置字体
        HSSFFont headerFont = workbook.createFont();
        headerFont.setColor(HSSFColor.VIOLET.index);
        headerFont.setFontName("楷体");
        headerStyle.setFont(headerFont);
        //表头内容
        for (int i = 0; i<headerStr.length; i++){
            //创建一个单元格
            HSSFCell headerCell = headerRow.createCell(i);
            headerCell.setCellStyle(headerStyle);
            headerCell.setCellValue(headerStr[i]);
        }
        //表体内容
        //设置表体单元格样式
        HSSFCellStyle bodyStyle = workbook.createCellStyle();
        //水平居中
        bodyStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //设置字体
        HSSFFont bodyFont = workbook.createFont();
        bodyFont.setColor(HSSFColor.BLUE.index);
        bodyFont.setFontName("宋体");
        bodyStyle.setFont(bodyFont);
        for(int row = 1; row<resource.size(); row++){
            //输出行数据
            String[] temp = resource.get(row);
            //创建行
            HSSFRow bodyRow = sheet.createRow(row);
            //循环创建列
            for(int cell = 0; cell<temp.length; cell++){
                HSSFCell bodyCell1 = bodyRow.createCell(cell);
                bodyCell1.setCellStyle(bodyStyle);
                bodyCell1.setCellValue(temp[cell]);
            }
        }
        //将Excel输出到文件
        workbook.write(outputStream);
    }
}

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐