简体   繁体   English

使用Apache POI实现Excel下载时,如何设置Excel文件名?

[英]How to set name of excel file when implementing excel download using apache poi?

I am working on a requirement to download excel file using Apache POI and spring MVC. 我正在研究使用Apache POI和spring MVC下载excel文件的要求。 I followed a tutorial and I could successfully complete the functionality. 我遵循了教程 ,可以成功完成功能。 However every time I click download, the filename of the downloaded excel is the ending part of string in the request URL 但是,每次单击下载时,下载的excel的文件名都是请求URL中字符串的结尾部分

eg: URL: http://localhost:8080/myproject/downloadExcel and the downloaded file will be with name download Excel. 例如:URL: http:// localhost:8080 / myproject / downloadExcel ,下载的文件将具有下载Excel的名称。

I want to dynamically create a filename and the downloaded file should have that name instead of the above. 我想动态创建一个文件名,下载的文件应使用该名称而不是上面的名称。 Can anyone help me how to achieve the required functionality? 谁能帮助我实现所需的功能?

@Controller public class MainController { @Controller公共类MainController {

/**
 * 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());
        }
    }

}

view configuration: 查看配置:

<?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>

View Resolver 查看解析器

<?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>

Pass the name of the file (you want to create) in the argument for the OutputStream you are writing the data to. 在要写入数据的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();

Since you are using servlet for making the file downloadable, you should do the following: 由于您正在使用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 header will instruct the browser to use the filename attribute as the file name for the download. Content-Disposition标头将指示浏览器将filename属性用作下载的文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM