目录
测试结果
表格数据
代码
依赖
/**
* C:\\Users\\Administrator\\Desktop\\testFile/abc.xlsx
* test 结果
* 13
* {"Sheet1":[{"s3":"ae","s4":"aa","s5":"aa","s1":"a","s2":"ab"},
* {"s3":"af","s4":"ab","s5":"ac","s1":"b","s2":"ac"}
* ]}
*
* C:\\Users\\Administrator\\Desktop\\testFile/ac.xls
*
* 13
* {"Sheet1":[{"s3":"ae","s4":"aa","s5":"aa","s1":"a","s2":"ab"},
* {"s3":"af","s4":"ab","s5":"ac","s1":"b","s2":"ac"} ]}
*/
package com.superman.uitl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
/**
* xlsx or xls 都 ok
* excel 转 json
*
* @author Administrator
*
*/
public class ExeclToJson {
private final static Logger logger = LoggerFactory.getLogger(ExeclToJson.class);
//private final static ObjectMapper mapper = new ObjectMapper();
/**
* C:\\Users\\Administrator\\Desktop\\testFile/abc.xlsx
* test 结果
* 13
* {"Sheet1":[{"s3":"ae","s4":"aa","s5":"aa","s1":"a","s2":"ab"},
* {"s3":"af","s4":"ab","s5":"ac","s1":"b","s2":"ac"}
* ]}
*
* C:\\Users\\Administrator\\Desktop\\testFile/ac.xls
*
* 13
* {"Sheet1":[{"s3":"ae","s4":"aa","s5":"aa","s1":"a","s2":"ab"},
* {"s3":"af","s4":"ab","s5":"ac","s1":"b","s2":"ac"} ]}
*/
//test
public static void main(String[] args) {
String fileUrl = "C:\\Users\\Administrator\\Desktop\\testFile/ac.xls";
JSONObject jo = ExeclToJson.excelToJson(fileUrl);
logger.info(jo.getJSONArray("Sheet1").size()+"");
logger.info(jo.toJSONString());
}
//excel 转 json
public static JSONObject excelToJson(String fileUrl){
try {
FileInputStream inp = new FileInputStream(fileUrl);
Workbook workbook = WorkbookFactory.create(inp);
//获取sheet数
int sheetNum = workbook.getNumberOfSheets();
JSONObject jsonObject = new JSONObject();
for (int s = 0; s < sheetNum; s++) {
// Get the Sheet of s.
Sheet sheet = workbook.getSheetAt(s);
//获取最大行数
int rownum = sheet.getPhysicalNumberOfRows();
if (rownum <= 1) {
continue;
}
//获取第一行
Row row1 = sheet.getRow(0);
//获取最大列数
int colnum = row1.getPhysicalNumberOfCells();
JSONArray jsonArray = new JSONArray();
for (int i = 1; i < rownum; i++) {
Row row = sheet.getRow(i);
if (row != null) {
// List
org.apache.poi
poi
3.14
org.apache.poi
poi-ooxml
3.14
dom4j
dom4j
1.6.1
ok