java按坐标读取数据excel的数据

临时有个项目要求按excel的坐标从exce对应的单元格中抓取相应的数据 

使用的是poi第三方包,贴代码(后台是SpringBoot框架):

后台代码:

package com.qm.jczx.common.validated;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;


import com.mongodb.gridfs.GridFSDBFile;
import com.qm.jczx.common.mongodb.MongoKit;
import com.qm.yqwl.core.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @version : 1.0.0
 * @Author : Byr
 * @Date : 2019/3/20 8:30
 * @Description :更具坐标读取excel单元格的数据
 */
@Slf4j
@RestController
@Api(value = "excel提取数据", description = "excel提取数据")
@RequestMapping("/getExcelDate")
public class ReadExcel {
    @Autowired
    CacheManager cacheManager;
    @Autowired
    MongoKit mongoKit; 
        public  List readExcel(Map map) throws IOException, InvalidFormatException {
            //从mongodb获得输入流
            GridFSDBFile f = mongoKit.findFile(map.get("fileId").toString());
            //存储页的list
            List sheetList= new ArrayList();
            try {
                // 获得工作簿
                Workbook workbook = WorkbookFactory.create(f.getInputStream());
                //本地文件
                //File file=new File("");
                // Workbook workbook = WorkbookFactory.create(file);
                // 获得工作表个数
                int sheetCount = workbook.getNumberOfSheets();
                // 遍历工作表
                for (int i = 0; i < sheetCount; i++) {
                    //储存行的List
                    List rowList=new ArrayList();
                    Sheet sheet = workbook.getSheetAt(i);
                    // 获得行数
                    int rows = sheet.getLastRowNum() + 1;
                    // 获得列数,先获得一行,在得到该行列数
                    Row tmp = sheet.getRow(i);
                    if (tmp == null) {
                        sheetList.add(i,null);
                        continue;
                    }
                    int cols = tmp.getPhysicalNumberOfCells();
                    // 读取数据
                    for (int row = 0; row < rows; row++) {
                        //储存列的数据
                        List coluList=new ArrayList();
                        Row r = sheet.getRow(row);
                        for (int col = 0; col < cols; col++) {
                            if(r!=null){
                                if(r.getCell(col)!=null){
                                    Object  value=null;
                                    if(r.getCell(col).getCellType() == HSSFCell.CELL_TYPE_NUMERIC && HSSFDateUtil.isCellDateFormatted(r.getCell(col))){
                                        Date date = r.getCell(col).getDateCellValue();
                                        //装换为时间格式
                                        String formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
                                        value=formatDate;
                                    }else {
                                        r.getCell(col).setCellType(CellType.STRING);
                                        value=r.getCell(col).getStringCellValue();
                                    }
                                    coluList.add(col,value);
                                }else {
                                    coluList.add(col,null);
                                }
                            }else {
                                coluList.add(col,null);
                            }
                        }
                        rowList.add(row,coluList);
                    }
                    sheetList.add(i,rowList);
                }
                System.out.println(sheetList);
                return sheetList;
            }catch (IOException e){
                e.printStackTrace();
            }
            return null;
        }
    /**
     * 将InputStream写入本地文件
     * @param input 输入流
     * @throws IOException IOException
     */
    public static String writeToLocal(InputStream input) throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        File file=new File("");
        FileOutputStream outputStream=null;
        String filePath=file.getCanonicalPath()+"/src/main/webapp/template/temp.xls";
       try{
           outputStream= new FileOutputStream(filePath);
           while ((index = input.read(bytes)) != -1) {
               outputStream.write(bytes, 0, index);
               outputStream.flush();
           }
           return filePath;
       }catch (IOException e){
           e.getMessage();
           e.printStackTrace();
       }finally {
           input.close();
           outputStream.close();
       }
     return null;
    }

    /**
     *
     * @param map fileId,excel坐标
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
   public synchronized String excelValue(Map map) throws Exception {
       List list=null;
       String mapValue=map.get("coordinate").toString();
       //sheet页码
       Integer sheetNumber=Integer.valueOf(mapValue.substring(0,2));
       //列数
       Integer column=Integer.valueOf(stringToAscii(mapValue.substring(2,3).toUpperCase()))-65;
       //行数
       Integer row=Integer.valueOf(mapValue.substring(3,mapValue.length()))-1;
       //缓存key值
       String key= map.get("fileId").toString();
        try {
            //将值存入缓存中,根据自己情况来写
            Cache cache=cacheManager.getCache("myCache");
            if(cache.get(key)!=null){
                list=(List) cache.get(key).get();
            }else {
                list=this.readExcel(map);
                cache.put(key,list);
            }
            //根据坐标取出数据(根据excel的不同sheet的值也不一样,可根据自己的情况调试除sheet的页数)
            List sheetList=(List)list.get(sheetNumber);
            List rowList= (List) sheetList.get(row);
            String excelValue=rowList.get(column).toString();
            System.out.println(excelValue);
            return excelValue;
        }catch (Exception e){
            e.printStackTrace();
        }
         return null;
    }

    /**
     * 将字符转换为AsCll
     * @param value
     * @return
     */
    public static String stringToAscii(String value) {
        StringBuffer sbu = new StringBuffer();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if(i != chars.length - 1)
            {
                sbu.append((int)chars[i]).append(",");
            }
            else {
                sbu.append((int)chars[i]);
            }
        }
        return sbu.toString();
    }
    /**接收前台传过来的值
     * 根据excel坐标读取excel单元格的数据
     * 注!工作表数量暂时为1~3页为准,后面的数据可能会乱 待后期优化
     * @Author:Byr
     * @param fileId excel的fileId
     * @param coordinateArr 单元格坐标 (格式为:工作表的第几页+坐标:例如:取出第一个工作表第A1的数据的坐标为:01A01)
     * @throws Exception
     */
    @PostMapping(value = "/readExcelDate", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public synchronized Result<Map> readExcelDate(@RequestParam(value = "fileId") String fileId,
                                     @RequestParam(value = "coordinateArr") String coordinateArr) throws Exception {
        //将字符串转换为数组型
      com.alibaba.fastjson.JSONArray array= com.alibaba.fastjson.JSONArray.parseArray(coordinateArr);
        Map<Integer,String> mapValue=new HashMap();
        for(int i=0;i<array.size();i++){
            Map map=new HashMap();
            map.put("fileId",fileId);
            map.put("coordinate",array.get(i));
            String excelValue=this.excelValue(map);
            mapValue.put(i,excelValue);
        }
        return Result.success(mapValue);
    }
}

前台代码:

 toReadExcel(){
                let that=this;     
                let coordinateArr1=["01C3","01I33","01U16","03I33","01I34","03I34","01U16"]//单元格坐标 (格式为:工作表的第几页+坐标:例如:取出第一个工作表第A1的数据的坐标为:01A01)

                let mapValue=[];
                const p1={}
                const param1 = {
                    params:{
                        fileId: this.fileList[0].fileId,
                        coordinateArr: JSON.stringify(coordinateArr1)
                    }
                };
                that.$http.post('/getExcelDate/readExcelDate',p1,param1).then((result) => {
                    console.log("excel数据", result);
                    if (result.data.isSuccess) {
                        mapValue=result.data.data;
                        var date=new Date(mapValue[0]);
                        var timestamp=date.getTime();
                        var D=(parseFloat(mapValue[2])*28.836)/(8.314*(22+273.15));
                        var ROUND=(1-D/7900)/(1-D/280.8989).toFixed(5);
                        var pAveQ=parseFloat(mapValue[3])/ROUND;
                        var pAveH=parseFloat(mapValue[5])/ROUND;
                          
                    }
                });
            },

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java程序示例,可供参考: 需求1:读取excel中的x与y轴坐标值以及对应的高度。 ``` import java.io.File; import java.io.FileInputStream; import java.io.IOException; 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.ss.usermodel.WorkbookFactory; public class ReadExcel { public static void main(String[] args) throws IOException { FileInputStream inputStream = new FileInputStream(new File("data.xlsx")); Workbook workbook = WorkbookFactory.create(inputStream); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { Cell xCell = row.getCell(0); Cell yCell = row.getCell(1); Cell heightCell = row.getCell(2); double x = xCell.getNumericCellValue(); double y = yCell.getNumericCellValue(); double height = heightCell.getNumericCellValue(); System.out.println("X: " + x + ", Y: " + y + ", Height: " + height); } workbook.close(); inputStream.close(); } } ``` 需求2:赋予每个坐标点3种状态,初始状态为0 ``` import java.util.ArrayList; import java.util.List; public class Coordinate { private double x; private double y; private double height; private List<Integer> states; public Coordinate(double x, double y, double height) { this.x = x; this.y = y; this.height = height; this.states = new ArrayList<>(); this.states.add(0); this.states.add(0); this.states.add(0); } public double getX() { return x; } public double getY() { return y; } public double getHeight() { return height; } public List<Integer> getStates() { return states; } public void setStates(List<Integer> states) { this.states = states; } } ``` 需求3:读取excel表格中的风速风向数据,根据给定的计算公式计算蔓延因子 ``` import java.io.File; import java.io.FileInputStream; import java.io.IOException; 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.ss.usermodel.WorkbookFactory; public class SpreadFactor { private double windSpeed; private double windDirection; private double temperature; private double humidity; private double spreadFactor; public SpreadFactor(double windSpeed, double windDirection, double temperature, double humidity) { this.windSpeed = windSpeed; this.windDirection = windDirection; this.temperature = temperature; this.humidity = humidity; this.spreadFactor = 0; } public double calculate() { // 根据给定的计算公式计算蔓延因子 // ... return spreadFactor; } public static void main(String[] args) throws IOException { FileInputStream inputStream = new FileInputStream(new File("data.xlsx")); Workbook workbook = WorkbookFactory.create(inputStream); Sheet sheet = workbook.getSheetAt(1); for (Row row : sheet) { Cell windSpeedCell = row.getCell(0); Cell windDirectionCell = row.getCell(1); Cell temperatureCell = row.getCell(2); Cell humidityCell = row.getCell(3); double windSpeed = windSpeedCell.getNumericCellValue(); double windDirection = windDirectionCell.getNumericCellValue(); double temperature = temperatureCell.getNumericCellValue(); double humidity = humidityCell.getNumericCellValue(); SpreadFactor spreadFactor = new SpreadFactor(windSpeed, windDirection, temperature, humidity); double factor = spreadFactor.calculate(); System.out.println("Wind Speed: " + windSpeed + ", Wind Direction: " + windDirection + ", Temperature: " + temperature + ", Humidity: " + humidity + ", Spread Factor: " + factor); } workbook.close(); inputStream.close(); } } ``` 需求4:给定初始起火点,即状态从0到1,给定初始速度,乘以蔓延因子得到八个方向上的蔓延速度,乘以时间步长5分钟,得到新的蔓延范围 ``` import java.util.ArrayList; import java.util.List; public class Spread { private List<Coordinate> coordinates; private double initialSpeed; private double timeStep; public Spread(List<Coordinate> coordinates, double initialSpeed, double timeStep) { this.coordinates = coordinates; this.initialSpeed = initialSpeed; this.timeStep = timeStep; } public void ignite(int x, int y) { for (Coordinate coordinate : coordinates) { if (coordinate.getX() == x && coordinate.getY() == y) { List<Integer> states = coordinate.getStates(); states.set(0, 1); states.set(1, 0); states.set(2, 0); } } } public void spread(double spreadFactor) { List<Coordinate> newCoordinates = new ArrayList<>(); for (Coordinate coordinate : coordinates) { List<Integer> states = coordinate.getStates(); if (states.get(0) == 1) { double speed = initialSpeed * spreadFactor * timeStep; double x = coordinate.getX(); double y = coordinate.getY(); double height = coordinate.getHeight(); newCoordinates.add(new Coordinate(x - speed, y, height)); newCoordinates.add(new Coordinate(x - speed, y + speed, height)); newCoordinates.add(new Coordinate(x, y + speed, height)); newCoordinates.add(new Coordinate(x + speed, y + speed, height)); newCoordinates.add(new Coordinate(x + speed, y, height)); newCoordinates.add(new Coordinate(x + speed, y - speed, height)); newCoordinates.add(new Coordinate(x, y - speed, height)); newCoordinates.add(new Coordinate(x - speed, y - speed, height)); } else if (states.get(0) == 0 && (states.get(1) == 1 || states.get(2) == 1)) { // 根据给定的规则计算状态变化 // ... newCoordinates.add(coordinate); } else { newCoordinates.add(coordinate); } } coordinates = newCoordinates; } public static void main(String[] args) { List<Coordinate> coordinates = new ArrayList<>(); coordinates.add(new Coordinate(0, 0, 10)); coordinates.add(new Coordinate(0, 1, 20)); coordinates.add(new Coordinate(0, 2, 30)); coordinates.add(new Coordinate(1, 0, 40)); coordinates.add(new Coordinate(1, 1, 50)); coordinates.add(new Coordinate(1, 2, 60)); coordinates.add(new Coordinate(2, 0, 70)); coordinates.add(new Coordinate(2, 1, 80)); coordinates.add(new Coordinate(2, 2, 90)); Spread spread = new Spread(coordinates, 10, 5); spread.ignite(1, 1); spread.spread(0.5); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值