【问题标题】:How to save a excel file to users download path in java如何将excel文件保存到java中的用户下载路径
【发布时间】:2019-03-08 09:27:30
【问题描述】:

在我的项目中,我将创建一个ExcelWorkBook 并将一些数据写入该工作簿。 写完后我希望它保存到用户下载路径,所以尝试了以下代码:

XSSFWorkbook hwb=new XSSFWorkbook();  
XSSFSheet sheet =  hwb.createSheet("Exam Marks Entry");
//writing data to workbook

//then targeting users download path as follows
String home = System.getProperty("user.home");
File file = new File(home+"/Downloads/"+mainDisplayDto.getClassName()+" "+mainDisplayDto.getExamName()+".xlsx");

FileOutputStream fileOut =  new FileOutputStream(file);  
hwb.write(fileOut);

上述代码仅在应用程序在本地时有效(将工作簿保存到下载路径),但在应用程序在VPS上时无效。

应用程序不在本地运行时,如何将其保存到用户系统下载文件夹中?

如果将数据写入工作簿后,我可以在系统中打开excel文件,以便用户将其保存在任何地方,我的问题也将得到解决。

谁能帮我解决这个问题?

【问题讨论】:

  • 有网络服务器和网络浏览器吗?
  • web 服务器是一个 linux 服务器(VPS)

标签: java apache-poi fileoutputstream


【解决方案1】:

您可以在锚标记或按钮元素上使用 window.location.href="",当用户单击它时,您应该调用您的程序,其中响应返回 excel 表并在用户的下载文件夹中下载。

例如: window.location.href="/downloadExcelMarks" 是我指的是我的控制器的网址。它调用我的控制器,我将发送 excel 作为我的控制器的响应,如下所示:

XSSFWorkbook hwb=new XSSFWorkbook();
XSSFSheet sheet =  hwb.createSheet("Exam Marks Entry");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=marks.xlsx");
ServletOutputStream outStream = response.getOutputStream();
workbook.write(outStream); // Write workbook to response.
outStream.close();

【讨论】:

  • 我正在使用 spring mvc 它可以在 spring mvc 中工作吗?
  • 当然可以。只需将此代码放入您用于下载的控制器中。它会起作用的。
  • 所以这个请求是用户从浏览器发起的吧?
  • 是的,它是一个 ajax 调用,我有 json 对象要使用该 url 发送
  • 谢谢@Jai Prakash,它对我的​​代码进行了一些更改,将发布整个答案
【解决方案2】:

我想您可以理解,将文件保存到下载位置是浏览器的属性。您可以将下载的浏览器默认位置设置为文件系统中的任何位置。如何指定响应存储在不同用户使用不同文件系统的用户系统中。

【讨论】:

  • 是的,它是正确的。我可以直接打开那个excel而不保存,这样用户就可以随意保存了
  • 如果您想要用户填写数据的 excel 数据,在您的应用程序中,您应该为用户提供上传选项,他们可以上传填写的 Excel 表格,您应该解析 excel 和读取数据。
  • 用户没有填写数据,他们将给 A 类作为输入,我们需要获取 A 类的数据,它会与程序一起正常,但在用户系统中保存或打开惹麻烦
  • 所以你可以下载excel但无法打开它不是吗?
  • 我什至没有下载直接使用java保存它
【解决方案3】:

我在@Jai Prakash 建议的帮助下解决了问题,并更改了我的 ajax 调用和我的一些 java 代码,请查看代码

ajax 调用:

      $(document).on("click","#downlodMarksSheet",function(event){
            var examCatId=$("#meExamMainEV").val();     
            var classId=$(".mainContainer #meClass").val();  
            var secId=$(".mainContainer #sectionId").val() ;
            var stringFromDate=$(".mainContainer #FromDate").val();
            var stringToDate=$(".mainContainer #ToDate").val();
            var url = contextPath+"/excel/exportExcel/"+classId+"/"+secId+"/"+examCatId+"/"+stringFromDate.replace(/\//g, "-")+"/"+stringToDate.replace(/\//g, "-");
            window.location.href=url;
        });

**java code :**

@GetMapping(value = "/exportExcel/{classId}/{secId}/{examCatId}/{stringFromDate}/{stringToDate}")
    public HttpServletResponse updateStudentGeneralDetailss(@PathVariable("classId") int classId,
            @PathVariable("secId") int secId,@PathVariable("examCatId") int examCatId,
            @PathVariable("stringFromDate") String stringFromDate,
            @PathVariable("stringToDate") String stringToDate,HttpServletRequest request,HttpServletResponse response) {

        try { 



            String filename="";
            XSSFWorkbook hwb=new XSSFWorkbook();  
            XSSFSheet sheet =  hwb.createSheet("Exam Marks Entry");  
            XSSFRow subsHead=   sheet.createRow(0);
            subsHead.createCell(1).setCellValue("");
            XSSFRow subSubsIdsHead=   sheet.createRow(1);
            XSSFRow subSubs=   sheet.createRow(2);



            response.setContentType("application/vnd.ms-excel");

            ServletOutputStream outStream = response.getOutputStream();


            XSSFColor myColor = new XSSFColor(Color.YELLOW);

            XSSFCellStyle style = hwb.createCellStyle();  
            style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
            style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
            style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());

            style.setBorderBottom(CellStyle.BORDER_THIN);
            style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
            style.setBorderLeft(CellStyle.BORDER_THIN);
            style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
            style.setBorderRight(CellStyle.BORDER_THIN);
            style.setRightBorderColor(IndexedColors.BLACK.getIndex());
            style.setBorderTop(CellStyle.BORDER_THIN);
            style.setTopBorderColor(IndexedColors.BLACK.getIndex());  



                ExmaExportDTO mainDisplayDto  = service.getExamPartten(examCatId, classId, secId,stringFromDate.replaceAll("-", "/"),stringToDate.replaceAll("-", "/"));

            List<ExamStudentMarksDisplaySubjectsDTO> subjects=  mainDisplayDto.getSubjectsList();
            int i=2;
            int formCol=2;
            int subsubCol=2;

            sheet.addMergedRegion(new CellRangeAddress(0,0,0,1));
            sheet.addMergedRegion(new CellRangeAddress(1,1,0,1));

            Cell cel=subSubs.createCell(0); 
            cel.setCellStyle(style);  
            cel.setCellValue("Student Ids");

            Cell cel1=subSubs.createCell(1);
            cel1.setCellStyle(style);  
            cel1.setCellValue("Student Name");

            /*iterating subjects*/
            for(ExamStudentMarksDisplaySubjectsDTO subObj : subjects)
            {  
                Cell cell=subsHead.createCell(formCol);
                cell.setCellStyle(style);
                cell.setCellValue(subObj.getSubjectName());;
                List<ExamStudentMarksDisplaySubjectsSubCatDTO> subSubj=subObj.getSubCatMarks();

                int subSubjLen=subSubj.size(); 

                int toCol=formCol+subSubjLen;

                sheet.addMergedRegion(new CellRangeAddress(0,0,formCol,toCol-1));

                for(ExamStudentMarksDisplaySubjectsSubCatDTO subsubObj :subSubj)
                {
                    Cell cell1=subSubsIdsHead.createCell(subsubCol);
                    cell1.setCellStyle(style);
                    cell1.setCellValue(subsubObj.getExmSubjectSubCategory());
                    Cell cell2=subSubs.createCell(subsubCol);
                    cell2.setCellStyle(style);  
                    cell2.setCellValue(subsubObj.getSubCatName()+"("+subsubObj.getSubCatMaxMarks()+")");
                    subsubCol++;
                }

                formCol=subSubjLen+formCol;;  
                i++;        
            }
            Cell cella=subSubs.createCell(subsubCol);
            cella.setCellStyle(style);
            cella.setCellValue("Description");

            Cell cell1a=subSubs.createCell(subsubCol+1);
            cell1a.setCellStyle(style);
            cell1a.setCellValue("No.of Working Days");

            Cell cell2a=subSubs.createCell(subsubCol+2);
            cell2a.setCellStyle(style);
            cell2a.setCellValue("No.of Present Days");


            List<ExamStudentMarksDisplayStudentsDTO> students=mainDisplayDto.getStudentList();
            /*iterating students*/
            int j=3;
            for(ExamStudentMarksDisplayStudentsDTO stu : students)
            {
                XSSFRow rows=   sheet.createRow(j);
                Cell cell3=rows.createCell(0);
                cell3.setCellStyle(style);
                cell3.setCellValue(stu.getStudentId());
                String lastName="";
                if(stu.getLastMame() !=null)
                {
                    lastName=stu.getLastMame();
                }
                Cell cell4=rows.createCell(1);
                cell4.setCellStyle(style); 
                cell4.setCellValue(stu.getFirstName()+" "+lastName);
                j++;
            }  

            response.setHeader("Content-Disposition", "attachment; filename="+mainDisplayDto.getClassName()+""+mainDisplayDto.getExamName()+".xlsx");
            hwb.write(outStream);
            outStream.close();

        }
catch (Exception e) {  
    e.printStackTrace();
}
        return response;
    }

谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    相关资源
    最近更新 更多