poi excel content-Type设置
时间: 2023-12-17 09:01:57 浏览: 318
在使用POI操作Excel文件时,可以通过设置Content-Type来指定生成的Excel文件的类型。具体步骤如下:
1. 导入相关包
```java
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
```
2. 在Controller中设置Content-Type
```java
@RequestMapping("/downloadExcel")
public void downloadExcel(HttpServletResponse response) {
try {
//创建Workbook对象
Workbook workbook = new XSSFWorkbook();
//Workbook workbook = new HSSFWorkbook();
//设置Content-Type
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//response.setContentType("application/vnd.ms-excel");
//设置文件名
response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");
//response.setHeader("Content-Disposition", "attachment;filename=test.xls");
//将Workbook写入OutputStream
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
```
其中,Content-Type分别为application/vnd.openxmlformats-officedocument.spreadsheetml.sheet和application/vnd.ms-excel,分别对应xlsx和xls格式的Excel文件。
需要注意的是,在使用XSSFWorkbook时,Content-Type应该设置为application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;在使用HSSFWorkbook时,Content-Type应该设置为application/vnd.ms-excel。
阅读全文