栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

java解析表格excel,获取数据,放到map/json中

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java解析表格excel,获取数据,放到map/json中

思想:

1、先获取到文件,第一行通常参数名,再逐一拿到每一行参数对应的数据。
2、再对每一行数据进行处理 。
3、存放到map中方便以键值对处理。

技术:

1、导入依赖:org.apache.poi
org.apache.poi poi 3.14
2、配置spring boot项目小帮手
3、开始解构excel

一、获取文件并读取,案例中用到的是本地文件。

//获取到表
  File file = new File("d:/follow.xlsx");
  //读取内容
  FileInputStream inputStream = new FileInputStream(file);

二、创建XSSFWorkbook对象,拿到该文件中的表,因为一个excel文件中可以有子表(索引0 1 2 3…),所以还需锁定子表;最后拿到第一行的属性值。

//拿到读取的表内容
XSSFWorkbook wb = new XSSFWorkbook(inputStream); 
System.out.println("length:"+wb.getNumberOfSheets());
//获取到第二个子表
XSSFSheet sheet = wb.getSheetAt(1);
String sheetName = sheet.getSheetName();//表的名称
System.out.println("sheetName=" + sheetName);
//获取标题栏---第0行
XSSFRow titleRow = sheet.getRow(0);

三、从第二行开始遍历,拿到每一行数据,并放在map中。

		//存放结果数据
		Map objectMap = new HashMap<>();
		int count = 0;
		for(int rowIndex = 1 ; rowIndex < sheet.getPhysicalNumberOfRows() - 1;rowIndex++){
          	XSSFRow xssfRow = sheet.getRow(rowIndex);//获取到表的某行信息
            if(xssfRow == null){//如果为空进入下一个循环
                continue;
            }
           	//放入map中,方便入值(键值对),JSON也不错。
           	Map map = new HashMap<>();
           	for (int cellIndex = 0; cellIndex < xssfRow.getLastCellNum() - 1; cellIndex++) {
                Cell titleCell = titleRow.getCell(cellIndex);//获取每一列标题
                Cell xssfCell = xssfRow.getCell(cellIndex);//获取某行某列的值
                String value = " ";
                if(xssfCell != null){
                    value = getCellValue(xssfCell,titleCell);//数据格式的转换
                }
                map.put(titleCell.toString(),value);//存放在map中
        	}
            //放入大map中
            objectMap.put(count,map);
            count++;
   	 	}

四、这样objectMap中每个键值对就是一行数据。
更加方便获取。

for(int i = 0;i
           System.out.println(objectMap.get(i));
        }

最终代码:

package com.antPaige.file.controller;

import com.antPaige.file.service.date_followService;
import com.microsoft.schemas.office.visio.x2012.main.CellType;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@ResponseBody
public class date_follow {
    @Autowired
    private date_followService followService;
    @RequestMapping("/data_follow")
    public Object retrieveExcel() throws Exception {
        //获取到表
        File file = new File("d:/follow.xlsx");
        //读取内容
        FileInputStream inputStream = new FileInputStream(file);
        //XSSFWorkbook获取到内容
        XSSFWorkbook wb = new XSSFWorkbook(inputStream);
        System.out.println("length:"+wb.getNumberOfSheets());
        //获取到Sheet2表
        XSSFSheet sheet = wb.getSheetAt(1);
        String sheetName = sheet.getSheetName();//表的名称
        System.out.println("sheetName=" + sheetName);

        //获取标题栏---第0行
        XSSFRow titleRow = sheet.getRow(0);
        
        //存放最终结果
        Map objectMap = new HashMap<>();
        int count = 0;
        //第二行开始,遍历每一行
        System.out.println(sheet.getPhysicalNumberOfRows());
        for(int rowIndex = 1 ; rowIndex < sheet.getPhysicalNumberOfRows() - 1;rowIndex++){
            XSSFRow xssfRow = sheet.getRow(rowIndex);//获取到表的某行信息
            xssfRow.getPhysicalNumberOfCells();
            //Cell testTitle = titleRow.getCell(14);//第十四列标题
            if(xssfRow == null){//如果为空进入下一个循环
                continue;
            }
            Map map = new HashMap<>();
			for (int cellIndex = 0; cellIndex < xssfRow.getLastCellNum() - 1; cellIndex++) {
                Cell titleCell = titleRow.getCell(cellIndex);//获取每一列标题
                Cell xssfCell = xssfRow.getCell(cellIndex);//获取某行某列的值
                String value = " ";
                if(xssfCell != null){
                    value = getCellValue(xssfCell,titleCell);//数据格式的转换
                }
                map.put(titleCell.toString(),value);//存放在map中
        }
        objectMap.put(count,map);
        count++;
        }
        //查看拿到的数据
        Set key1 = objectMap.keySet();
        Iterator it = key1.iterator();
        while(it.hasNext()){
            Object t = it.next();
            System.out.println(t+":"+objectMap.get(t));
        }
        return "OK";
    }
    public String getCellValue(Cell cell,Cell title) {
        String temp = "";
        if (cell == null) {
            return temp;
        }
        int flag = cell.getCellType();//获取类型
        if(title.toString().equals("create_on") || title.toString().equals("institution_code")){//设置公式的
            flag = 2;
        }
        switch (flag) {
            case Cell.CELL_TYPE_STRING:
                return cell.getRichStringCellValue().getString();
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    Date date = cell.getDateCellValue();
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    temp = df.format(date);
                    return temp;
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case Cell.CELL_TYPE_FORMULA:
                cell.setCellType(Cell.CELL_TYPE_STRING);
                //System.out.println("--------"+cell.getStringCellValue());
                temp = cell.getStringCellValue();
                if(title.toString().equals("create_on") ){
                    temp = cell.getStringCellValue() + "000";
                }
                return temp ;

            default:
                return temp;
        }
    }
    public Map getMap(){
        Map result = new HashMap<>();
        return result;
    }
}
转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1040634.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号