poi excel content-Type设置
时间: 2023-12-17 07:01:57 浏览: 358
在使用POI操作Excel文件时,可以通过设置Content-Type来指定生成的Excel文件的类型。具体步骤如下:
- 导入相关包
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;
- 在Controller中设置Content-Type
@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。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)