我的项目有这个要求,其中用户上传的CSV文件,这必须推送到sql server数据库。我知道我们可以使用Spring batch来处理大量的记录。但是我找不到任何教程/示例代码来满足我的这一要求。我遇到的所有教程都只是将CSV文件名和内存中的数据库硬编码到其中,如下所示:
https://spring.io/guides/gs/batch-processing/
用户输入文件按预定时间在共享驱动器位置可用,文件名前缀为例如: stack_overlfow_dd-MM-yyyy HH:mm,每天如何轮询网络共享驱动器每5-10分钟至少一小时,如果它与正则表达式匹配,则上传到数据库。我如何首先从共享位置获取csv文件,并将其存储在内存或其他地方,然后配置spring batch以将其作为输入读取。这里的任何帮助都将不胜感激。提前感谢
发布于 2018-09-03 16:41:57
我遇到的所有教程都是硬编码的CSV文件名和内存数据库
您可以在官方repo here中找到示例。Here is an example,其中输入文件名不是硬编码的,而是作为作业参数传递。
如何首先从共享位置获取csv文件并将其存储在内存或其他地方,然后配置spring batch将其作为输入读取。
您可以分两步进行:将文件下载到本地,然后读取/处理/写入数据库(请参阅https://stackoverflow.com/a/52110781/5019386)。
如何每隔5-10分钟轮询一次网络共享驱动器,如果它与正则表达式匹配,则每天至少轮询一个小时,然后上载到数据库。
定义作业后,可以使用以下命令将其安排为在需要时运行:
中有描述
有关作业调度here的更多详细信息。
发布于 2018-09-02 03:30:16
我相信你的问题已经在here得到了回答。
问题的作者甚至上传了他的工作结果的存储库:https://github.com/PriyankaBolisetty/SpringBatchUploadCSVFileToDatabase/tree/master/src/main/java/springbatch_example
您可以使用JCIFS API方法SmbFile.listFiles(String wildcard)检索和过滤共享驱动器中的文件列表。
发布于 2018-09-02 03:34:45
你可以制作一个服务层,可以处理excel文件,从文件中读取数据,并构造java对象保存到数据库中。在这里,我使用了apache POI来解析Excel数据并从excel表格中读取数据。
public class FileUploadService {
@Autowired
FileUploadDao fileUploadDao;
public String uploadFileData(String inputFilePath) {
Workbook workbook = null;
Sheet sheet = null;
try {
workbook = getWorkBook(new File(inputFilePath));
sheet = workbook.getSheetAt(0);
/*Build the header portion of the Output File*/
String headerDetails = "EmployeeId,EmployeeName,Address,Country";
String headerNames[] = headerDetails.split(",");
/*Read and process each Row*/
ArrayList < ExcelTemplateVO > employeeList = new ArrayList < > ();
Iterator < Row > rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
//Read and process each column in row
ExcelTemplateVO excelTemplateVO = new ExcelTemplateVO();
int count = 0;
while (count < headerNames.length) {
String methodName = "set" + headerNames[count];
String inputCellValue = getCellValueBasedOnCellType(row, count++);
setValueIntoObject(excelTemplateVO, ExcelTemplateVO.class, methodName, "java.lang.String", inputCellValue);
}
employeeList.add(excelTemplateVO);
}
fileUploadDao.saveFileDataInDB(employeeList);
} catch (Exception ex) {
ex.printStackTrace();
}
return "Success";
}
https://stackoverflow.com/questions/52129980
复制相似问题