Java解析生成excel文件(精简)

maven依赖: 

        
        
            com.alibaba
            easyexcel
            1.1.2-beta4
        

工具类代码:


import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.duoku.crmpackageadmin.bean.DataModel;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtil {
    //解析excel文件
    public static List parseExcel(MultipartFile file) throws IOException {
        List list = new ArrayList<>();
        ExcelReader reader = new ExcelReader(new BufferedInputStream(file.getInputStream()), null, new AnalysisEventListener() {
            @Override
            public void invoke(Object o, AnalysisContext analysisContext) {
                List rows = (List) o; //读取一行数据
                if(StringUtils.isNotBlank(rows.get(0))) {
                    list.add(rows.get(0));   //获取当前行的第一列
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                //读取完整个文件作的处理
            }
        });
        reader.read();
        return list;
    }
    //创建生成excel
    public static File createExcel(List list) {
        try {
            File files = new File("temp");
            if(!files.isDirectory()) {
                files.mkdirs();
            }
            File file = new File(files,"用户文件.xlsx");
            if(!file.exists()) {
                file.createNewFile();
            }
            OutputStream os = new FileOutputStream(file);
            ExcelWriter writer = EasyExcelFactory.getWriter(os);
            Sheet sheet = new Sheet(1,0,DataModel.class); //设置模型数据,下面会讲到
            sheet.setSheetName("用户id");
            List modelList = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(list)) {
                for(Object o:list) {
                    DataModel d = new DataModel();
                    d.setUserId(String.valueOf(o));
                    modelList.add(d);
                }
            }
            writer.write(modelList,sheet);
            writer.finish();
            os.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    //下载excel(没有需求可以不看)
    public static void downloadFile(HttpServletResponse response,File file ) {
        String fileName = "用户文件.xlsx";// 文件名
        //设置文件路径
        if (file != null && file.exists() && file.length() > 0) {
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO-8859-1"));// 设置文件名
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            try {
                response.getWriter().write("file not exist");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

模型类代码:


import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.Data;

@Data
public class DataModel extends BaseRowModel {

    @ExcelProperty(value = "用户id", index = 0)
    private String userId;        //可以设置多个属性 value列名 index第几列,0开始
}

 

你可能感兴趣的:(Java工具类)