Action
@Action(value = "uploadCsvFile", interceptorRefs = @InterceptorRef("biolimsDefaultStack"))
public void uploadCsvFile() throws Exception {
//模板文件id 存在文件表中
String fileId = getParameterFromRequest("fileId");
//无关属性 用来区分级别
String pType = getParameterFromRequest("pType");
Map<String, Object> map = new HashMap<String, Object>();
try {
map = instrumentService.getCsvContent(fileId,pType);
map.put("success", true);
} catch (Exception e) {
e.printStackTrace();
map.put("success", false);
}
HttpUtils.write(JsonUtils.toJsonString(map));
}
Service
@WriteOperLog
@WriteExOperLog
@Transactional(rollbackFor = Exception.class)
public Map<String, Object> getCsvContent(String fileId, String pType) throws Exception {
//查询文件所在路径
FileInfo fileInfo = commonDAO.get(FileInfo.class, fileId);
String filepath = fileInfo.getFilePath();
//创建文件对象
File a = new File(filepath);
//导入表
Instrument instrument = null;
Map<String, Object> map = new HashMap<String, Object>();
//错误信息
String error = "";
String prompt = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
User user = (User) ActionContext.getContext().getSession().get(com.biolims.common.SystemConstants.USER_SESSION_KEY);
if (a.isFile()) {
InputStream is = new FileInputStream(filepath);
if (is != null) {
CsvReader reader = new CsvReader(is, Charset.forName("GBK"));
reader.readHeaders();// 去除表头
//定位行数 方便返回错误信息行
int i = 2;
while (reader.readRecord()) {
Instrument instrument1 = commonDAO.get(Instrument.class, reader.get("设备编号"));
if (instrument1==null && !"".equals(reader.get("设备编号"))){
instrument = new Instrument();
if (StringUtils.isNotBlank(reader.get("设备编号"))) {
instrument.setId(reader.get("设备编号"));
} else {
error += " 设备编号为空请填写,";
}
instrument.setCreateUser(user);
instrument.setCreateDate(new Date());
if (StringUtils.isNotBlank(reader.get("设备名称"))) {
instrument.setName(reader.get("设备名称"));
}
if (StringUtils.isNotBlank(error)) {
if (error.endsWith(",")) {
error = error.substring(0, error.length()-1);
}
prompt += "The " + i + " Line:" + error + ";";
break;
}
if ("".equals(error)){
commonDAO.saveOrUpdate(instrument);
}
}
i++;
}
}
}
map.put("prompt", prompt);
return map;
}