如何上传CSV文件然后自动将数据插入数据库?

tex*_*e11 4 java spring file-upload web-applications supercsv

我有基于Java的Spring MVC应用程序,它也使用Spring安全性.我正在使用hibernate作为此Web应用程序的ORM工具.

以下是我的要求 -

用户可以使用Web浏览器上传CSV文件.已知CSV文件的格式包含以下5个字段:

userId, location, itemId, quantity, tranDate
001, NY, 00A8D5, 2, 12/31/2012
002, MN, 00A7C1, 10, 12/22/2012
.
.

像这样大约有100行.

我在项目中使用Super CSV:

private void readWithCsvBeanReader(String CSV_FILENAME) throws Exception {

    String CSV_FILENAME = "\\\\Serv01\\Files\\QueryResult.csv";
    //String CSV_FILENAME = "C:\\Files\\QueryResult.csv";
    ICsvBeanReader beanReader = null;
    try {
        beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME),
                CsvPreference.STANDARD_PREFERENCE);

        // the header elements are used to map the values to the bean (names
        // must match)
        final String[] header = beanReader.getHeader(true);
        // get Cell Processor
        final CellProcessor[] processors = getProcessors();
Run Code Online (Sandbox Code Playgroud)

这里我正在阅读CSV文件的内容然后使用Hibernate,我正在插入它.

这很好,因为我在本地或在Windows共享上提供CSV路径.

String CSV_FILENAME = "\\\\Serv01\\Files\\QueryResult.csv";
or via this:
String CSV_FILENAME = "C:\\Files\\QueryResult.csv"; 
Run Code Online (Sandbox Code Playgroud)
  1. 如何实现此要求,以便使用Spring MVC通过网页上的按钮提供CSV文件路径位置?

  2. 是否也可以从远程位置自动获取文件,以便我将文件上传到FTP位置,然后程序可以连接到远程ftp位置并按计划处理文件?

PS:我是文件操作的新手,如果有人可以指向一些文章那么它会很棒.

Ada*_*ent 6

像这样大约有100行.

不要将CSV保存为tmp文件,因为Spring的Mulitpart将为您执行此操作并直接插入行(请求可能需要更长时间才能处理,但鉴于您目前的表面知识,您可以担心以后优化)

private void readWithCsvBeanReader(MultipartFile uploadedFile) throws Exception {

    ICsvBeanReader beanReader = null;
    try {
        beanReader = new CsvBeanReader(new InputStreamReader(uploadedFile.getInputStream()),
                CsvPreference.STANDARD_PREFERENCE);

        // the header elements are used to map the values to the bean (names
        // must match)
        final String[] header = beanReader.getHeader(true);
        // get Cell Processor
        final CellProcessor[] processors = getProcessors();
Run Code Online (Sandbox Code Playgroud)

让你的控制器像:

@RequestMapping(value = "/add", method=RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
// call your csv parsing code.
}
Run Code Online (Sandbox Code Playgroud)

确保你的FORM看起来像:

<h1>Add a File for testing</h1>
<form method="post" action="/add" class="well form-vertical" enctype="multipart/form-data">
    <input type="file" name="file" />
    <button type="submit" class="btn">{{actionLabel}}</button>
</form>
Run Code Online (Sandbox Code Playgroud)

注意到 enctype

对于输入和输出,您应该了解Java的IO装饰器模式.

我建议你尽量简单,以便学习基础知识.然后担心添加更强大的解决方案/库.