|
@@ -4,6 +4,7 @@ import java.util.ArrayList;
|
|
|
import java.util.List;
|
|
|
import java.util.stream.Collectors;
|
|
|
|
|
|
+import cn.hutool.core.collection.CollectionUtil;
|
|
|
import cn.hutool.core.io.FileUtil;
|
|
|
import cn.hutool.core.text.csv.CsvData;
|
|
|
import cn.hutool.core.text.csv.CsvReader;
|
|
@@ -77,10 +78,7 @@ public class CsvUtils {
|
|
|
* @param csvFilePath path
|
|
|
*/
|
|
|
public static JSONArray fileCsvToJson(String csvFilePath) {
|
|
|
- CsvReader reader = CsvUtil.getReader();
|
|
|
- // 从文件中读取CSV数据
|
|
|
- CsvData data = reader.read(FileUtil.file(csvFilePath), CharsetUtil.CHARSET_GBK);
|
|
|
- List<CsvRow> rows = data.getRows();
|
|
|
+ List<CsvRow> rows = getCsvRowList(csvFilePath);
|
|
|
// 获取CSV表头,即第一行数据
|
|
|
List<String> headers = rows.get(0).getRawList();
|
|
|
// 去除第一行,保留后续数据
|
|
@@ -103,10 +101,50 @@ public class CsvUtils {
|
|
|
* @return 参数名称列表
|
|
|
*/
|
|
|
public static List<String> getCsvHeaders(String csvFilePath) {
|
|
|
+ List<CsvRow> rows = getCsvRowList(csvFilePath);
|
|
|
+ return rows.get(0).getRawList();
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 根据头名称(参数名称)获取csv文件中参数数据
|
|
|
+ *
|
|
|
+ * @param csvFilePath csv文件地址
|
|
|
+ * @return 参数名称列表
|
|
|
+ */
|
|
|
+ public static JSONArray getCsvDataByHeaders(String csvFilePath, List<String> headerNames) {
|
|
|
+ List<CsvRow> rows = getCsvRowList(csvFilePath);
|
|
|
+ // 获取CSV表头,即第一行数据
|
|
|
+ List<String> headers = rows.get(0).getRawList();
|
|
|
+ List<Integer> indexList = new ArrayList<>();
|
|
|
+ headerNames.forEach(name -> {
|
|
|
+ int index = headers.indexOf(name);
|
|
|
+ if (index != -1) {
|
|
|
+ indexList.add(index);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ if (CollectionUtil.isEmpty(indexList)) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ // 去除第一行,保留后续数据
|
|
|
+ List<CsvRow> dataLines = rows.subList(1, rows.size());
|
|
|
+ JSONArray jsonArray = new JSONArray();
|
|
|
+ for (CsvRow line : dataLines) {
|
|
|
+ JSONObject jsonObject = new JSONObject();
|
|
|
+ for (int i = 0; i < headers.size(); i++) {
|
|
|
+ // 参数索引位置
|
|
|
+ if (indexList.contains(i)) {
|
|
|
+ jsonObject.putOnce(headers.get(i), line.getRawList().get(i));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ jsonArray.add(jsonObject);
|
|
|
+ }
|
|
|
+ return jsonArray;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static List<CsvRow> getCsvRowList(String csvFilePath) {
|
|
|
CsvReader reader = CsvUtil.getReader();
|
|
|
// 从文件中读取CSV数据
|
|
|
CsvData data = reader.read(FileUtil.file(csvFilePath), CharsetUtil.CHARSET_GBK);
|
|
|
- List<CsvRow> rows = data.getRows();
|
|
|
- return rows.get(0).getRawList();
|
|
|
+ return data.getRows();
|
|
|
}
|
|
|
}
|