1
0
mirror of https://github.com/dairuoqi/Springboot-rock-admin.git synced 2026-09-24 06:46:35 +00:00

读取EXCEL方法

This commit is contained in:
dairuoqi
2018-08-27 10:32:02 +08:00
parent 7eac92fd93
commit e9fe19d37b
12 changed files with 387 additions and 29 deletions

0
.gitignore vendored Normal file → Executable file
View File

24
pom.xml Normal file → Executable file
View File

@@ -70,19 +70,14 @@
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.0.3</version>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.0.3</version>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.8</version>
</dependency>
<!-- druid数据库连接池 -->
@@ -98,6 +93,13 @@
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
</dependencies>
<build>

BIN
src/main/.DS_Store vendored

Binary file not shown.

View File

@@ -0,0 +1,6 @@
package com.rock.geological.constant;
public class ApiConstant {
public static String PYTHON_URL = "http://192.168.0.104:8888/api/data";
}

View File

@@ -0,0 +1,171 @@
package com.rock.geological.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class CSV2JSONHelper {
private String fileName = null;
private static BufferedReader br = null;
private static List<String> list;
public CSV2JSONHelper(String fileName) throws Exception {
this.fileName = fileName;
list = new ArrayList<>();
br = new BufferedReader(new FileReader(fileName));
String stemp;
while ((stemp = br.readLine()) != null) {
list.add(stemp);
}
}
public List getList() {
return list;
}
/**
* 获取行数
*
* @return
*/
public static int getRowNum() {
return list.size();
}
/**
* 获取列数
*
* @return
*/
private int getColNum() {
if (!list.toString().equals("[]")) {
if (list.get(0).contains(",")) {// csv为逗号分隔文件
return list.get(0).split(",").length;
} else if (list.get(0).trim().length() != 0) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
/**
* 获取指定行
*
* @param index
* @return
*/
private static String getRow(int index) {
if (list.size() != 0) {
return (String) list.get(index);
} else {
return null;
}
}
/**
* 获取指定列
*
* @param index
* @return
*/
public String getCol(int index) {
if (this.getColNum() == 0) {
return null;
}
StringBuffer sb = new StringBuffer();
String tmp = null;
int colnum = this.getColNum();
if (colnum > 1) {
for (Iterator it = list.iterator(); it.hasNext(); ) {
tmp = it.next().toString();
sb = sb.append(tmp.split(",")[index] + ",");
}
} else {
for (Iterator it = list.iterator(); it.hasNext(); ) {
tmp = it.next().toString();
sb = sb.append(tmp + ",");
}
}
String str = new String(sb.toString());
str = str.substring(0, str.length() - 1);
return str;
}
/**
* 获取某个单元格
*
* @param row
* @param col
* @return
*/
public String getString(int row, int col) {
String temp = null;
int colnum = this.getColNum();
if (colnum > 1) {
temp = list.get(row).toString().split(",")[col];
} else if (colnum == 1) {
temp = list.get(row).toString();
} else {
temp = null;
}
return temp;
}
private static void CsvClose() throws Exception {
br.close();
}
/**
* 去表头
**/
public String removehead(String str) {
String[] str_1 = str.split(",");
String sb = new String();
for (int i = 1; i < str_1.length; i++) {
sb = sb + str_1[i] + ",";
}
return sb;
}
private static String[] getHeader() {
//1.第一行就是Header
String HeaderString = list.get(0);
return HeaderString.split(",");
}
public static JSONArray readCSV(String path) {
JSONArray array = new JSONArray();
try {
new CSV2JSONHelper(path);
String[] Header = getHeader();
int row = getRowNum();
for (int i = 1; i < row; i++) {
JSONObject jsonobject = new JSONObject(16, true);
String RowValue = getRow(i);
String[] cell = RowValue.split(",");
for (int j = 0; j < cell.length; j++) {
jsonobject.put(Header[j], cell[j]);
}
array.add(jsonobject);
}
CsvClose();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return array;
}
}

View File

@@ -1,9 +1,8 @@
package com.rock.geological.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Maps;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
@@ -30,7 +29,6 @@ public class Excel2JSONHelper {
}
private static boolean fileNameFileter(File file) {
boolean endsWith = false;
if (file != null) {
@@ -41,7 +39,6 @@ public class Excel2JSONHelper {
}
private static Row getHeaderRow(Sheet sheet, int index) {
Row headerRow = null;
if (sheet != null) {
@@ -58,8 +55,6 @@ public class Excel2JSONHelper {
//String类型
case Cell.CELL_TYPE_STRING:
return cell.getRichStringCellValue().getString();
//number类型
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
@@ -108,6 +103,7 @@ public class Excel2JSONHelper {
/**
* 读取excel并按照列顺序返回
*
* @param file
* @param headerIndex
* @param headType
@@ -127,22 +123,21 @@ public class Excel2JSONHelper {
FormulaEvaluator formula = wb.getCreationHelper().createFormulaEvaluator();
for (int r = headerIndex + 1; r <= sheet.getLastRowNum(); r++) {
//保证JSONArray有序
JSONObject jsonObject = new JSONObject(16,true);
JSONObject jsonObject = new JSONObject(16, true);
Row dataRow = sheet.getRow(r);
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
// LinkedHashMap<String, Object> map = Maps.newLinkedHashMap();
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);
jsonObject.put(key,value);
// map.put(key, value);
jsonObject.put(key, value);
}
}
jsonArray.add(jsonObject);
}
} catch (Exception e) {
e.printStackTrace();
}

View File

@@ -0,0 +1,112 @@
package com.rock.geological.utils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
public class VisitApiUtil {
//post方式访问api接口 返回 string 后面按需要转JsonObject或者JsonArray
public static <T> String visitApiPost(String POST_URL, T object) throws Exception {
URL url = new URL(POST_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
String JsonStr = JSONObject.toJSONString(object, SerializerFeature.WriteMapNullValue);
out.write(JsonStr.getBytes("utf-8"));
System.out.println(JsonStr.toString());
out.flush();
out.close();
// 读取响应 --从内存中的缓冲区里面读
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
reader.close();
connection.disconnect();
return sb.toString();
}
//get请求远程api 返回String
public static String visitApiGet(String GET_URL, Map<String, String> parameters) {
String result = "";
BufferedReader in = null;// 读取响应输入流
StringBuffer sb = new StringBuffer();// 存储参数
String params = "";// 编码之后的参数
HttpURLConnection httpConn = null;
JSONObject jSONObject = null;
try {
// 编码请求参数
if (parameters.size() == 1) {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(
java.net.URLEncoder.encode(parameters.get(name),
"UTF-8"));
}
params = sb.toString();
} else {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(
java.net.URLEncoder.encode(parameters.get(name),
"UTF-8")).append("&");
}
String temp_params = sb.toString();
params = temp_params.substring(0, temp_params.length() - 1);
}
String full_url = GET_URL + "?" + params;
// 创建URL对象
URL connURL = new URL(full_url);
// 打开URL连接
httpConn = (HttpURLConnection) connURL.openConnection();
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
// 建立实际的连接
httpConn.connect();
// 响应头部获取
Map<String, List<String>> headers = httpConn.getHeaderFields();
// 定义BufferedReader输入流来读取URL的响应,并设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn
.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
//json字符串 --> json对象
// jSONObject = JSON.parseObject(result.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
httpConn.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result.toString();
}
}

View File

@@ -1,14 +1,17 @@
package com.rock.geological.web.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rock.geological.constant.ApiConstant;
import com.rock.geological.res.ResponseMgr;
import com.rock.geological.utils.CSV2JSONHelper;
import com.rock.geological.utils.Excel2JSONHelper;
import com.rock.geological.utils.FileUtil;
import com.rock.geological.utils.VisitApiUtil;
import com.rock.geological.web.pojo.ApiProcess;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
@@ -18,16 +21,49 @@ import java.util.Date;
@RequestMapping("/excel")
public class ExportController {
private final String basePath = "/Users/rock/Desktop/geological/geological/excel/";
private final String baseExcelPath = "/Users/rock/Desktop/geological/geological/excel/";
private final String baseCsvPath = "/Users/rock/Desktop/geological/geological/csv/";
@PostMapping("/importExcel")
public ResponseEntity<?> importExcel(MultipartFile multipartFile) throws Exception {
FileUtil.makeDir(basePath);
File newFile = new File(basePath + new Date().getTime() + multipartFile.getOriginalFilename());
FileUtil.makeDir(baseExcelPath);
File newFile = new File(baseExcelPath + new Date().getTime() + multipartFile.getOriginalFilename());
multipartFile.transferTo(newFile);
JSONArray jsonArray = Excel2JSONHelper.readExcel(newFile, 0, 2);
return ResponseEntity.ok(ResponseMgr.successWithData(jsonArray));
}
@PostMapping("/importCsv")
public ResponseEntity<?> importCsv(MultipartFile multipartFile) throws Exception {
FileUtil.makeDir(baseCsvPath);
String path = baseCsvPath + new Date().getTime() + multipartFile.getOriginalFilename();
File newFile = new File(path);
multipartFile.transferTo(newFile);
JSONArray jsonArray = CSV2JSONHelper.readCSV(path);
return ResponseEntity.ok(ResponseMgr.successWithData(jsonArray));
}
/**
* api 读取 excel 返回前端JsonArray
*/
@PostMapping("/readExcel")
public ResponseEntity<?> readExcel(@RequestBody ApiProcess params) {
// String path = "/Users/rock/Desktop/现阶段须二岩性图odd.xlsx";
try {
String excelPath = VisitApiUtil.visitApiPost(ApiConstant.PYTHON_URL,params);
File excelFile = new File(excelPath);
JSONArray jsonArray = Excel2JSONHelper.readExcel(excelFile, 0, 2);
return ResponseEntity.ok(ResponseMgr.successWithData(jsonArray));
} catch (Exception e) {
e.printStackTrace();
}
return ResponseEntity.ok(ResponseMgr.err());
}
}

View File

@@ -0,0 +1,31 @@
package com.rock.geological.web.pojo;
public class ApiProcess {
private String module;
private int action;
private String path;
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public int getAction() {
return action;
}
public void setAction(int action) {
this.action = action;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}

Binary file not shown.

View File

@@ -1,4 +1,8 @@
spring:
servlet:
multipart:
max-file-size: 10Mb
max-request-size: 100Mb
datasource:
url: jdbc:mysql://127.0.0.1:3306/geological
username: root
@@ -22,7 +26,6 @@ spring:
#设置静态资源路径,多个以逗号分隔
static-locations: classpath:static/,file:static/
jpa:
hibernate:
# 实体类有更新时,数据库表更新
@@ -31,3 +34,5 @@ spring:
format_sql: true
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect

View File