java Excel工具类 ExcelUtils

package com.wqh.fsrm.common.util;


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 javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Excel表格操作类
 */
public class ExcelUtils {

    //表格各种列类型
    public static final int CELL_TYPE_NUMERIC = 0;
    public static final int CELL_TYPE_STRING = 1;
    public static final int CELL_TYPE_FORMULA = 2;
    public static final int CELL_TYPE_BLANK = 3;
    public static final int CELL_TYPE_BOOLEAN = 4;
    public static final int CELL_TYPE_ERROR = 5;

    /**
     * 上传文件获取 文件路径
     * @param fileName
     * @param mFile
     * @return
     * @throws IOException
     */
    public static String getFileUrl(String fileName, MultipartFile mFile) throws IOException {
        String tmpPath = "/tmp/upload/excels/";
        File directory = new File(tmpPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        String path = directory.getAbsolutePath()+"/"+System.currentTimeMillis() + "_" + mFile.getOriginalFilename() + "_" + UUID.randomUUID() + ".xlsx";
        File file = new File(path);
        if (!file.exists()) {
            file.createNewFile();
        }
        mFile.transferTo(file);
        return path;
    }

    /**
     * 读取excel
     * @param path
     */
    public static void readExcel(String path){
        try {
            File file = new File(path);
            String fileName = file.getName();
            InputStream is = new FileInputStream(path);
            Workbook wb = isExcel2003(fileName) ? new HSSFWorkbook(is) : new XSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);
            for (int i = sheet.getFirstRowNum()+1; i < sheet.getPhysicalNumberOfRows(); i++) {
                Row row = sheet.getRow(i);
                for(int j = row.getFirstCellNum(); j < row.getLastCellNum();j++){
                    Cell cell = row.getCell(j);
                    String value = String.valueOf(getCellValue(cell));
                    // 具体的业务逻辑
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 读取excel
     * @param path
     */
    public static List<Map<String,Object>> readExcelToList(String path){
        List<Map<String,Object>> list = new ArrayList<>();
        try {
            File file = new File(path);
            String fileName = file.getName();
            InputStream is = new FileInputStream(path);
            Workbook wb = isExcel2003(fileName) ? new HSSFWorkbook(is) : new XSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);
            Row rowFirst = sheet.getRow(0);
            for (int i = sheet.getFirstRowNum()+1; i < sheet.getPhysicalNumberOfRows(); i++) {
                Row row = sheet.getRow(i);
                Map<String,Object> map = new HashMap<>();
                for(int j = row.getFirstCellNum(); j < row.getLastCellNum();j++){
                    Cell cell = row.getCell(j);
                    String value = String.valueOf(getCellValue(cell));
                    String key =String.valueOf(getCellValue(rowFirst.getCell(j)));
                    // 具体的业务逻辑
                    map.put(key,value);
                }
                list.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


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

    public static Object getCellValue(Cell cell) throws Exception {
        Object value;
        //判断是否为null或空串
        if (cell == null || cell.toString().trim().equals("")) {
            return "";
        }
        CellType cellType = cell.getCellType();
        switch (cellType) {
            case NUMERIC:
                value = cell.getNumericCellValue();
                break;
            case STRING:
                value = cell.getStringCellValue();
                break;
            case BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case FORMULA:
                throw new Exception("excel cell unSupport expression");
            case ERROR:
                throw new Exception("excel cell type excel");
            case BLANK:
                value = "";
                break;
            default:
                throw new Exception("known excel cellType");
        }
        return value;
    }


    public static String generateTimestampNo() {
        String tradeNo = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        tradeNo += sdf.format(new Date());
        Random rand = new Random(Thread.currentThread().getId() ^ System.nanoTime());
        tradeNo += new DecimalFormat("0000").format(rand.nextInt(10000));
        return tradeNo;
    }

    /**
     * 创建导出excel
     * @param info
     * @return
     */
    public static void createExportExcel(Map<String,Object> info){
        try {
            HttpServletResponse response = (HttpServletResponse) info.get("response");
            String fileName = (String)info.get("fileName");
            List<String> columnTitles = (List<String>)info.get("columnTitles");
            List<List<String>> datas = (List<List<String>>) info.get("datas");
            int columnWidth = 16;
            if(info.containsKey("columnWidth")){
                columnWidth = (Integer)info.get("columnWidth");
            }
            List<Integer> columnWidthList = (List<Integer>)info.get("columnWidthList");//各列列宽
            short rowHeight = 400;
            if(info.containsKey("rowHeight")){//行高
                rowHeight = Short.parseShort(info.get("rowHeight").toString());
            }
            OutputStream os = null;
            os = response.getOutputStream();// 取得输出流
            response.reset();// 清空输出流
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String((fileName +generateTimestampNo()).getBytes("GB2312"), "8859_1")
                    + ".xlsx");// 设定输出文件头
            response.setContentType("application/msexcel");// 定义输出类型

            Workbook workbook = new HSSFWorkbook();
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setWrapText(true);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            Sheet sheet = workbook.createSheet();
            sheet.setDefaultColumnWidth(columnWidth);
            if(columnWidthList != null && columnWidthList.size() == columnTitles.size()){
                for(int i=0;i<columnWidthList.size();i++){
                    sheet.setColumnWidth(i,columnWidthList.get(i)*256);
                }
            }
            int rowIndex = 0;
            Row row = sheet.createRow(rowIndex);
            row.setHeight(rowHeight);
            for(int i=0;i<columnTitles.size();i++){
                row.createCell(i).setCellValue(columnTitles.get(i));
            }
            rowIndex++;
            for(int i=0;i<datas.size();i++){
                List<String> data = datas.get(i);
                row = sheet.createRow(rowIndex);
                row.setHeight(rowHeight);
                for(int j=0;j<data.size();j++){
                    Cell cell = row.createCell(j);
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue(data.get(j));
                }
                rowIndex++;
            }
            workbook.write(os);
            os.flush();
            os.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        List<Map<String,Object>> list = readExcelToList("D:/5.xlsx");
        System.out.println(list);
    }
}

Java中有很多可以用于Excel导入的工具类,其中比较常用的是Apache POI库。Apache POI是一个开源的Java API,用于处理Microsoft Office格式的文件,包括Excel文件。 使用Apache POI可以实现Excel文件的读取和写入操作。下面是一个简单的Java Excel导入工具类的示例: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ExcelUtils { public static List<List<String>> readExcel(String filePath) throws IOException { List<List<String>> data = new ArrayList<>(); FileInputStream fis = new FileInputStream(new File(filePath)); Workbook workbook = new XSSFWorkbook(fis); Sheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); List<String> rowData = new ArrayList<>(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); String cellValue = ""; if (cell.getCellType() == CellType.STRING) { cellValue = cell.getStringCellValue(); } else if (cell.getCellType() == CellType.NUMERIC) { cellValue = String.valueOf(cell.getNumericCellValue()); } rowData.add(cellValue); } data.add(rowData); } workbook.close(); fis.close(); return data; } } ``` 上述代码中的`readExcel`方法可以读取Excel文件,并将每个单元格的值存储在一个二维列表中返回。你只需要将Excel文件的路径作为参数传递给该方法即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浮生若梦01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值