簡體   English   中英

使用 JAVA 下載 CSV 文件

[英]Downloading a CSV file using JAVA

我是一名新實習生和 java 開發人員,致力於 web 應用程序。 目前,我的應用程序允許用戶在單擊生成按鈕時生成 csv 文件。 這個應用程序打算在之后部署在公司的服務器上,但我不知道如何讓這個文件可供未來的用戶下載。 我在互聯網上查看了使用 HttpServlet 不斷彈出的答案,但是我似乎無法理解它是如何工作的,或者它是否真的是我需要的。 任何人都可以為我提供任何指導或答案。

非常感謝。

PS:如果相關的話,該公司將 SpringBoot 用於其應用程序。

我在這里發布一個小代碼片段。 希望這可以幫助。

服務器端代碼

@RequestMapping(value = "/report", method=RequestMethod.GET)
    void generateReport(HttpServletResponse response,
            HttpServletRequest request) throws IOException {
        
        String outputFileName = "C:\\Users\\Avik\\" + ".csv";
        // Change the file location
        File reportFile = new File(outputFileName);
          
        try { 
            // create FileWriter object with file as parameter 
            FileWriter outputfile = new FileWriter(reportFile); 
      
            // create CSVWriter object filewriter object as parameter 
            CSVWriter writer = new CSVWriter(outputfile); 
      
            // create a List which contains String array 
            List<String[]> data = new ArrayList<String[]>(); 
            data.add(new String[] { "StudentID", "Name", "Mobile"});
            for (Student st : students) {
                // Add Student Details
                data.add(new String[] {st.id,
                        st.name,
                        st.mobile);
            }
            writer.writeAll(data); 
      
            // closing writer connection 
            writer.close(); 
        } 
        catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } 
        // Download section
        String mimeType = "text/csv";
        response.setContentType(mimeType);
        String reportFileName = "report.csv";
        response.setHeader("Content-Disposition", String.format("attachment; filename=\""+reportFileName+"\""));
        response.setContentLength((int) reportFile.length());
        InputStream inputStream = new BufferedInputStream(new FileInputStream(reportFile));

        FileCopyUtils.copy(inputStream, response.getOutputStream());
        response.flushBuffer();

    }

客戶端代碼(HTML)

<a id="reportDownload" target="_blank" href="/report">Generate Report</a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM