Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在使用ApachePOI实现excel下载时,如何设置excel文件的名称?_Java_Spring Mvc_Download_Apache Poi - Fatal编程技术网

Java 在使用ApachePOI实现excel下载时,如何设置excel文件的名称?

Java 在使用ApachePOI实现excel下载时,如何设置excel文件的名称?,java,spring-mvc,download,apache-poi,Java,Spring Mvc,Download,Apache Poi,我正在研究使用ApachePOI和SpringMVC下载excel文件的需求。我遵循了一个步骤,我可以成功地完成功能。但是,每次单击“下载”时,下载的excel的文件名都是请求URL中字符串的结尾部分 例如:网址: 下载的文件名为下载Excel 我想动态创建一个文件名,下载的文件应该有这个名称,而不是上面的名称。有人能帮我实现所需的功能吗 @控制器 公共类主控制器{ /** * Handle request to the default page */ @RequestMapping(val

我正在研究使用ApachePOI和SpringMVC下载excel文件的需求。我遵循了一个步骤,我可以成功地完成功能。但是,每次单击“下载”时,下载的excel的文件名都是请求URL中字符串的结尾部分

例如:网址: 下载的文件名为下载Excel

我想动态创建一个文件名,下载的文件应该有这个名称,而不是上面的名称。有人能帮我实现所需的功能吗

@控制器 公共类主控制器{

/**
 * Handle request to the default page
 */
@RequestMapping(value = "/", method = RequestMethod.GET)
public String viewHome() {
    return "home";
}

/**
 * Handle request to download an Excel document
 */
@RequestMapping(value = "/downloadExcel", method = RequestMethod.GET)
public ModelAndView downloadExcel() {
    // create some sample data
    List<Book> listBooks = new ArrayList<Book>();
    listBooks.add(new Book("Effective Java", "Joshua Bloch", "0321356683",
            "May 28, 2008", 38.11F));
    listBooks.add(new Book("Head First Java", "Kathy Sierra & Bert Bates",
            "0596009208", "February 9, 2005", 30.80F));
    listBooks.add(new Book("Java Generics and Collections",
            "Philip Wadler", "0596527756", "Oct 24, 2006", 29.52F));
    listBooks.add(new Book("Thinking in Java", "Bruce Eckel", "0596527756",
            "February 20, 2006", 43.97F));
    listBooks.add(new Book("Spring in Action", "Craig Walls", "1935182358",
            "June 29, 2011", 31.98F));

    // return a view which will be resolved by an excel view resolver
    return new ModelAndView("excelView", "listBooks", listBooks);
}
}


    public class ExcelBuilder extends AbstractExcelView {

    @Override
    protected void buildExcelDocument(Map<String, Object> model,
            HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // get data model which is passed by the Spring container
        List<Book> listBooks = (List<Book>) model.get("listBooks");

        // create a new Excel sheet
        HSSFSheet sheet = workbook.createSheet("Java Books");
        sheet.setDefaultColumnWidth(30);

        // create style for header cells
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("Arial");
        style.setFillForegroundColor(HSSFColor.BLUE.index);
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setColor(HSSFColor.WHITE.index);
        style.setFont(font);

        // create header row
        HSSFRow header = sheet.createRow(0);

        header.createCell(0).setCellValue("Book Title");
        header.getCell(0).setCellStyle(style);

        header.createCell(1).setCellValue("Author");
        header.getCell(1).setCellStyle(style);

        header.createCell(2).setCellValue("ISBN");
        header.getCell(2).setCellStyle(style);

        header.createCell(3).setCellValue("Published Date");
        header.getCell(3).setCellStyle(style);

        header.createCell(4).setCellValue("Price");
        header.getCell(4).setCellStyle(style);

        // create data rows
        int rowCount = 1;

        for (Book aBook : listBooks) {
            HSSFRow aRow = sheet.createRow(rowCount++);
            aRow.createCell(0).setCellValue(aBook.getTitle());
            aRow.createCell(1).setCellValue(aBook.getAuthor());
            aRow.createCell(2).setCellValue(aBook.getIsbn());
            aRow.createCell(3).setCellValue(aBook.getPublishedDate());
            aRow.createCell(4).setCellValue(aBook.getPrice());
        }
    }

}
/**
*将请求处理到默认页面
*/
@RequestMapping(value=“/”,method=RequestMethod.GET)
公共字符串viewHome(){
返回“家”;
}
/**
*处理下载Excel文档的请求
*/
@RequestMapping(value=“/downloadExcel”,method=RequestMethod.GET)
公共模型和视图下载Excel(){
//创建一些示例数据
List listBooks=new ArrayList();
添加(新书(“有效Java”,“Joshua Bloch”,“0321356683”,
“2008年5月28日”,38.11F);
添加(新书《头先Java》、《凯西·塞拉和伯特·贝茨》,
"0596009208","2005年2月9日",30.80F);;
添加(新书(“Java泛型和集合”,
“Philip Wadler”,“0596527756”,“2006年10月24日”,29.52F);
添加(新书《用Java思考》、《Bruce Eckel》、《0596527756》,
“2006年2月20日”,43.97F);
新增(新书:《行动中的春天》、《克雷格墙》、《1935182358》,
“2011年6月29日”,31.98F);
//返回将由excel视图解析程序解析的视图
返回新的ModelAndView(“excelView”、“listBooks”、“listBooks”);
}
}
公共类ExcelBuilder扩展了AbstractExcelView{
@凌驾
受保护的文档(地图模型,
HSSF工作簿、HttpServletRequest请求、HttpServletResponse响应)
抛出异常{
//获取Spring容器传递的数据模型
List listBooks=(List)model.get(“listBooks”);
//创建新的Excel工作表
HSSFSheet sheet=workbook.createSheet(“Java书籍”);
活页宽度(30);
//创建标题单元格的样式
CellStyle style=workbook.createCellStyle();
Font=workbook.createFont();
font.setFontName(“Arial”);
样式。setFillForegroundColor(HSSFColor.BLUE.index);
style.setFillPattern(CellStyle.SOLID\u前景);
字体设置权重(hssfont.BOLDWEIGHT\u BOLD);
font.setColor(HSSFColor.WHITE.index);
style.setFont(字体);
//创建标题行
HSSFRow表头=sheet.createRow(0);
header.createCell(0.setCellValue(“书名”);
header.getCell(0.setCellStyle(样式);
header.createCell(1.setCellValue(“作者”);
header.getCell(1.setCellStyle(样式);
header.createCell(2.setCellValue(“ISBN”);
header.getCell(2)、setCellStyle(style);
header.createCell(3.setCellValue(“发布日期”);
header.getCell(3)、setCellStyle(style);
header.createCell(4.setCellValue(“价格”);
header.getCell(4)、setCellStyle(style);
//创建数据行
int rowCount=1;
对于(图书目录:列表册){
HSSFRow aRow=sheet.createRow(rowCount++);
createCell(0.setCellValue(aBook.getTitle());
createCell(1).setCellValue(aBook.getAuthor());
createCell(2).setCellValue(aBook.getIsbn());
createCell(3).setCellValue(aBook.getPublishedDate());
createCell(4).setCellValue(aBook.getPrice());
}
}
}
视图配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="excelView" class="net.codejava.spring.ExcelBuilder" />

</beans>

视图解析器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="net.codejava.spring" />

   <bean id="viewResolver1" class="org.springframework.web.servlet.view.XmlViewResolver">
        <property name="order" value="1"/>
        <property name="location" value="/WEB-INF/views.xml"/>
    </bean>

    <bean id="viewResolver2"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="2"/>
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>


</beans>

在要向其写入数据的OutputStream的参数中传递要创建的文件名

String excelFileName = "C:/Test.xls"; //name of excel file

OutputStream fileOut = new FileOutputStream(excelFileName);

XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(sheetName) ;

//Write your code for the content generation here.

//write this workbook to an Outputstream.

wb.write(fileOut);
fileOut.flush();
fileOut.close();
由于您正在使用
servlet
使文件可下载,因此应执行以下操作:

String fileName = "MyFile.xls"; //Your file name here.

response.setContentType("application/vnd.ms-excel"); //Tell the browser to expect an excel file
response.setHeader("Content-Disposition", "attachment; filename="+fileName); //Tell the browser it should be named as the custom file name

HSSFWorkbook workbook = createExcel();
workbook.write(response.getOutputStream());
Content-Disposition
头将指示浏览器使用
filename
属性作为下载文件名。

在要将数据写入的输出流的参数中传递要创建的文件名

String excelFileName = "C:/Test.xls"; //name of excel file

OutputStream fileOut = new FileOutputStream(excelFileName);

XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(sheetName) ;

//Write your code for the content generation here.

//write this workbook to an Outputstream.

wb.write(fileOut);
fileOut.flush();
fileOut.close();
由于您正在使用
servlet
使文件可下载,因此应执行以下操作:

String fileName = "MyFile.xls"; //Your file name here.

response.setContentType("application/vnd.ms-excel"); //Tell the browser to expect an excel file
response.setHeader("Content-Disposition", "attachment; filename="+fileName); //Tell the browser it should be named as the custom file name

HSSFWorkbook workbook = createExcel();
workbook.write(response.getOutputStream());

Content-Disposition
标题将指示浏览器使用
filename
属性作为下载的文件名。

显示您正在下载的代码using@ScaryWombat代码添加显示您的代码using@ScaryWombat代码addedI必须下载文件,上面将在服务器磁盘上创建它,并为此添加了一节。试试看:)我必须下载文件,上面会在服务器磁盘上创建它,并为此添加了一节。试试看:)