我们经常有通过文件导入数据的需求,比如批量导入会员、导入配置、导入其他系统的数据。
通过Excel方式导入会比较麻烦,要导入类库,可以考虑把Excel转成CSV文件。
Excel->另存为->文件类型 CSV UTF-8(逗号分隔)->然后就变成如下的效果了。
在导入前把首行、后面的空白行删除即可。
Controller里面写一个方法,传入文件的路径filePath。解析文件用的是apache.commons的FileUtils,当然也可以直接通过文件流读取。
@RequestMapping("/import/reviewImport")
public Response<List<String>> importSellerReview(@RequestParam("filePath") String filePath) {
List<String> unSuccessLineNum = new ArrayList<>();
try {
List<String> lines =
FileUtils.readLines(new File(filePath), "UTF-8");
int lineNum = 0;
for (String line : lines) {
lineNum++;
List<String> arrayList = Arrays.asList(line.split(","));
List<String> afterTreatmentLine = linePretreatment(arrayList);
// 业务处理
}
} catch (IOException e) {
//错误日志记录
}
return Response.success(unSuccessLineNum);
}
private List<String> linePretreatment(List<String> lines) {
List<String> newLines = new ArrayList<>(lines.size());
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
if (line.startsWith("\"") && i != lines.size() - 1 && lines.get(i + 1).endsWith("\"")) {
String newLine = line + lines.get(i + 1);
newLines.add(newLine);
i++;
} else {
newLines.add(line);
}
}
return newLines;
}
private String getFromListDefaultNull(List<String> list, int index) {
String str = null;
try {
str = StringUtils.trim(list.get(index));
} catch (Exception e) {
ReviewLogUtils.businessWarn(bExceptionLogger, "importItemReview get column error", "REVIEW_SYSTEM_001");
}
return str;
}
pom.xml加入
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
注意点:
- 如果Excel内容中包含CSV的分隔符(默认逗号),会在内容外层加一对引号,可以先分割然后把错误分割的内容再组合起来。see linePretreatment(List lines)。
- 如果导出的内容变成 name,age,(空),(空),(空),那么很容易出现分割后List的长度不一致,get的时候会出现数组越界,统一处理下。see getFromListDefaultNull(List list, int index)