search
HomeJavajavaTutorialImplementation method of converting excel table to json in Java

本篇文章主要介绍了Java实现excel表格转成json的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

今天有个朋友问我,有没有excel表格到处json的方法,在网上找到了好几个工具,都不太理想,于是根据自己的需求,自己写了一个工具。

功能代码


package org.duang.test;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
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;

/**
 * excel表格转成json
 * @ClassName: Excel2JSONHelper  
 * @Description:TODO(这里用一句话描述这个类的作用)  
 * @author LiYonghui
 * @date 2017年1月6日 下午4:42:43
 */
public class Excel2JSONHelper {
  //常亮,用作第一种模板类型,如下图
  private static final int HEADER_VALUE_TYPE_Z=1;
  //第二种模板类型,如下图
  private static final int HEADER_VALUE_TYPE_S=2;
  public static void main(String[] args) {
     File dir = new File("e:\\2003.xls");
     Excel2JSONHelper excelHelper = getExcel2JSONHelper();
     //dir文件,0代表是第一行为保存到数据库或者实体类的表头,一般为英文的字符串,2代表是第二种模板, 
     JSONArray jsonArray = excelHelper.readExcle(dir, 0, 2);
     System.out.println(jsonArray.toString());;
  }

  /**
   *
   * 获取一个实例
   */
  private static Excel2JSONHelper getExcel2JSONHelper(){
    return new Excel2JSONHelper();
  }

  /**
   * 文件过滤
   * @Title: fileNameFileter  
   * @Description: TODO(这里用一句话描述这个方法的作用)  
   * @param:  
   * @author LiYonghui  
   * @date 2017年1月6日 下午4:45:42
   * @return: void   
   * @throws
   */
  private boolean fileNameFileter(File file){
    boolean endsWith = false;
    if(file != null){
      String fileName = file.getName();
      endsWith = fileName.endsWith(".xls") || fileName.endsWith(".xlsx");
    }
    return endsWith;
  }

  /**
   * 获取表头行
   * @Title: getHeaderRow  
   * @Description: TODO(这里用一句话描述这个方法的作用)  
   * @param: @param sheet
   * @param: @param index
   * @param: @return 
   * @author LiYonghui  
   * @date 2017年1月6日 下午5:05:24
   * @return: Row   
   * @throws
   */
  private Row getHeaderRow(Sheet sheet, int index){
    Row headerRow = null;
    if(sheet!=null){
      headerRow = sheet.getRow(index);
    }
    return headerRow;
  }

  /**
   * 获取表格中单元格的value
   * @Title: getCellValue  
   * @Description: TODO(这里用一句话描述这个方法的作用)  
   * @param: @param row
   * @param: @param cellIndex
   * @param: @param formula
   * @param: @return 
   * @author LiYonghui  
   * @date 2017年1月6日 下午5:40:28
   * @return: Object   
   * @throws
   */
  private Object getCellValue(Row row,int cellIndex,FormulaEvaluator formula){
    Cell cell = row.getCell(cellIndex);
    if(cell != null){
      switch (cell.getCellType()) {
      //String类型
      case Cell.CELL_TYPE_STRING:
        return cell.getRichStringCellValue().getString();

       //number类型
      case Cell.CELL_TYPE_NUMERIC:
        if (DateUtil.isCellDateFormatted(cell)) {
          return cell.getDateCellValue().getTime();
        } else {
          return cell.getNumericCellValue();
        }
      //boolean类型
      case Cell.CELL_TYPE_BOOLEAN:
        return cell.getBooleanCellValue();
      //公式  
      case Cell.CELL_TYPE_FORMULA:
        return formula.evaluate(cell).getNumberValue();
      default:
        return null;
      }
    }
    return null;
  }

  /**
   * 获取表头value
   * @Title: getHeaderCellValue  
   * @Description: TODO(这里用一句话描述这个方法的作用)  
   * @param: @param headerRow
   * @param: @param cellIndex 英文表头所在的行,从0开始计算哦
   * @param: @param type 表头的类型第一种 姓名(name)英文于实体类或者数据库中的变量一致
   * @param: @return 
   * @author LiYonghui  
   * @date 2017年1月6日 下午6:12:21
   * @return: String   
   * @throws
   */
  private String getHeaderCellValue(Row headerRow,int cellIndex,int type){
    Cell cell = headerRow.getCell(cellIndex);
    String headerValue = null;
    if(cell != null){
      //第一种模板类型
      if(type == HEADER_VALUE_TYPE_Z){
        headerValue = cell.getRichStringCellValue().getString();
        int l_bracket = headerValue.indexOf("(");
        int r_bracket = headerValue.indexOf(")");
        if(l_bracket == -1){
          l_bracket = headerValue.indexOf("(");
        }
        if(r_bracket == -1){
          r_bracket = headerValue.indexOf(")");
        }
        headerValue = headerValue.substring(l_bracket+1, r_bracket);
      }else if(type == HEADER_VALUE_TYPE_S){
      //第二种模板类型
        headerValue = cell.getRichStringCellValue().getString();
      }
    }
    return headerValue;
  }

  /**
   * 读取excel表格
   * @Title: readExcle  
   * @Description: TODO(这里用一句话描述这个方法的作用)  
   * @param: @param file
   * @param: @param headerIndex
   * @param: @param headType 表头的类型第一种 姓名(name)英文于实体类或者数据库中的变量一致
   * @author LiYonghui  
   * @date 2017年1月6日 下午6:13:27
   * @return: void   
   * @throws
   */
  public JSONArray readExcle(File file,int headerIndex,int headType){
    List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
    if(!fileNameFileter(file)){
      return null;
    }else{
      try {
        //加载excel表格
        WorkbookFactory wbFactory = new WorkbookFactory();
        Workbook wb = wbFactory.create(file);
        //读取第一个sheet页
        Sheet sheet = wb.getSheetAt(0); 
        //读取表头行
        Row headerRow = getHeaderRow(sheet, headerIndex);
        //读取数据
        FormulaEvaluator formula = wb.getCreationHelper().createFormulaEvaluator();
        for(int r = headerIndex+1; r<= sheet.getLastRowNum();r++){
          Row dataRow = sheet.getRow(r);
          Map<String, Object> map = new HashMap<String, Object>();
          for(int h = 0; h<dataRow.getLastCellNum();h++){
            //表头为key
            String key = getHeaderCellValue(headerRow,h,headType);
            //数据为value
            Object value = getCellValue(dataRow, h, formula);
            if(!key.equals("") && !key.equals("null") && key != null ){
              map.put(key, value);
            }
          }
          lists.add(map);
        }

      } catch (Exception e) {
        e.printStackTrace();
      } 
    }
    JSONArray jsonArray = JSONArray.fromObject(lists);
    return jsonArray;
  }
}

excel表格模板类型和调用方式

第一种 :用括号把实体类变量名称或者数据库字段名称括起来

调用方法如下:


  //表格的名称为2003.xls
  File file= new File("e:\\2003.xls");
  Excel2JSONHelper excelHelper = getExcel2JSONHelper();
  //字母表头为在第1行,第1种模板类型
  JSONArray jsonArray = excelHelper.readExcle(file, 1, 1);

第二种: 实体类变量名称或者数据库字段另起一行,如下两张图都行

调用方法如下:


  //表格的名称为2003.xls
  File file= new File("e:\\2003.xls");
  Excel2JSONHelper excelHelper = getExcel2JSONHelper();
  //字母表头为在第1行,第2种模板类型
  JSONArray jsonArray = excelHelper.readExcle(file, 1, 2);


  //表格的名称为2003.xls
  File file= new File("e:\\2003.xls");
  Excel2JSONHelper excelHelper = getExcel2JSONHelper();
  //字母表头为在第2行,第2种模板类型
  JSONArray jsonArray = excelHelper.readExcle(file, 2, 2);

jsonArray打印的结果

复制代码 代码如下:

[{"index":"1","name":"李逵","jobNum":"10004","dept":"开发部","job":"android工程师"},   
{"index":"2","name":"宋江","jobNum":"10001","dept":"总裁办","job":"总裁"}]

The above is the detailed content of Implementation method of converting excel table to json in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool