读取Excel表格以JSON形式数据输出

 第一步先导入以下包

   
      com.alibaba
      fastjson
      1.2.7
    
    
      org.apache.poi
      poi-ooxml
      3.13
    
    
      org.apache.poi
      poi
      3.17
    

第二步编写逻辑代码

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author:         轻狂书生FS
 * @Description:    读取Excel表格
 * @CreateDate:     2019/3/27 18:04
 * @Version:        1.0
*/
public class ExcelToJsonUtil {

    public static void main(String[] args) {
        ExcelToJsonUtil excelToJsonUtil = new ExcelToJsonUtil();
        Object object = excelToJsonUtil.ExcelToJson("D:\\表格导入\\1222.xls",null,7);
        System.out.println(object);
    }

    public JSONArray ExcelToJson(String filePath){
        return this.ExcelToJson(filePath,null,null);
    }

    /**
     * @Author:         轻狂书生FS
     * @Description:    读取Excel表格以json形式返回
     * @params          filePath:文件路径,startSheet:读取第几个sheet,startRow:从第几行开始读
     * @return
     * @CreateDate:     2019/3/27 18:06
     * @Version:        1.0
    */
    public JSONArray ExcelToJson(String filePath,Integer startSheet,Integer startRow) {
//        设置默认值0
        if (startSheet == null) {
            startSheet = 0;
        }
        if (startRow == null) {
            startRow = 0;
        }
        Workbook workbook = null;
        JSONArray jsons = new JSONArray();
        try {
            //适配xls格式和xlsx格式
            if (filePath.endsWith(".xls")) {
                workbook = new HSSFWorkbook(new FileInputStream(filePath));
            } else if (filePath.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(new FileInputStream(filePath));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Sheet sheet = workbook.getSheetAt(startSheet);
//        第startRow行,是表头部分
        Row row0 = sheet.getRow(startRow);
        Map map = new HashMap<>();
//        将表头的值放进map里面
        for (int i = 0; i < row0.getLastCellNum(); i++) {
            map.put(i, row0.getCell(i).toString());
        }
        for (int i = startRow + 1; i < sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            JSONObject object = new JSONObject();
//            读取的行不能为空且读取的列数等于表头的列数
            if ( row != null && map.size() == row.getLastCellNum() ) {
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    object.put(map.get(j),row.getCell(j).toString());
                }
                jsons.add(object);
            }
        }
        return jsons;
    }
}

第一次写工具类,不足之处请多多指教。谢谢阅读,欢迎转发。求关注

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