我正在尝试上传csv文件,如果上传成功,我打算将<strong>成功写入上传的csv。下面是我的代码(现在没有工作)
@RequestMapping(value = "/submitUploadCarForm")
public String uploadCar(CarUploadForm uploadform,HttpServletRequest request, Model model, BindingResult result) {
try {
CommonsMultipartFile file = uploadform.getFileData();
// parse csv file to list
csvList = CarCSVUtil.getCSVInputList(file.getInputStream());
for (CarCSVFileInputBean inputRecord : csvList) {
Car carentity = new Car();
carentity.setId(inputRecord.getId());
carentity.setName(inputRecord.getcarName());
carentity.setShortName(inputRecord.getcarShortName());
carentity.setEnvironment(inputRecord.getEnvironment());
carentity = this.Service.saveCar(carentity);
CarConfig compcfg = new CarConfig();
compcfg.setCar(carentity);
compcfg.setCarType(pickCarType(carTypes,inputRecord.getcarType()));
this.Service.saveCompCfg(compcfg);
inputRecord.setuploadstatus("success");<--- This is where i need help
}
}
catch (Exception e) {
e.printStackTrace();
result.rejectValue("name", "failureMsg","Error while uploading ");
model.addAttribute("failureMsg", "Error while uploading ");
}
return "view";
}
答案 0 :(得分:1)
我使用此代码导入csv文件,数据存储到database.Add opencsv jar文件到您的构建路径。
public String importCSV(@RequestParam("file") MultipartFile file,
HttpServletRequest req) throws IOException {
CsvToBean csv = new CsvToBean();
CSVReader reader = new CSVReader(new InputStreamReader(
file.getInputStream()), ',', '\"', 1);
ColumnPositionMappingStrategy maping = new ColumnPositionMappingStrategy();
maping.setType(tbBank.class);
String[] column = { "bankid", "bankname", "bankbranch" };
maping.setColumnMapping(column);
List banklist = csv.parse(maping, reader);
for (Object obj : banklist) {
tbBank bank = (tbBank) obj;
projectservice.insertBank(bank);
}
return "redirect:/bankview";
}