所需要的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.10</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
数据格式
处理代码简单示例
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.internal.util.JavaBeansUtil;
import org.springframework.util.ResourceUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xquant.platform.test.entity.pclass.TtrdSetInstruction;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class ExcelToJsonUtils {
public static void main(String[] args) {
String resourceLocation = "classpath:通用表查询 (22).xls";
String sheetName = "ttrd_set_instruction";
Class<?> targetType = TtrdSetInstruction.class;
File file = null;
try {
file = ResourceUtils.getFile(resourceLocation);
String fileName = file.getName();
boolean isValidFile = StringUtils.endsWithIgnoreCase(fileName, ".xlsx")
|| StringUtils.endsWithIgnoreCase(fileName, ".xls");
if (!isValidFile) {
throw new RuntimeException("不支持的格式文件" + fileName + "仅支持xlsx格式或xls格式");
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
}
Workbook workbook = null;
JSONArray jsonArray = new JSONArray();
try {
workbook = Workbook.getWorkbook(file);
Sheet sheet = workbook.getSheet(sheetName);
int columns = sheet.getColumns();
int rows = sheet.getRows();
if (columns < 1 || rows < 1) {
throw new RuntimeException("无有效数据");
}
Cell[] cells = sheet.getRow(0);
List<String> columnKeyList = new ArrayList<String>(columns);
for (Cell cell : cells) {
// 考虑到数据库列名与映射类的属性之间存在差异 将列名进行驼峰处理 该工具类来自于MyBatisGenerator
// 通过MyBatisGenerator可以根据数据库自动成数据层需要的简单java类、Mapper接口和xml文件
String key = JavaBeansUtil.getCamelCaseString(cell.getContents(), false);
columnKeyList.add(key);
}
for (int i = 1; i < rows; i++) {
JSONObject object = new JSONObject();
for (int j = 0; j < columns; j++) {
// 编译每一行的每一列数据 每一行都是一个JSONObject
object.put(columnKeyList.get(j), sheet.getCell(j, i).getContents());
}
jsonArray.add(object);
}
if (rows > 2) {
// 如果行数超过2 说明返回的数据是数组
targetType = Array.newInstance(targetType, 1).getClass();
}
// jsonArray.toJSONString()可以获取到json字符串;
Object result = JSON.toJavaObject(jsonArray, targetType);
System.out.println(result);
} catch (BiffException | IOException e) {
e.printStackTrace();
} finally {
if (workbook != null) {
workbook.close();
}
}
}
}