大家好,又见面了,我是全栈君
1.xml简介
<!-- excel use start -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="10"/>
</bean>
<bean id="viewExcel111" class="net.spring.controller.ViewExcel" />
<!-- excel use end -->
2.controller
@RequestMapping("excelAction")
public String excelAction(Map<String, Object> map){
// 传给ViewExcel的值
map.put("p1", "hello");
map.put("p2", "world");
return "viewExcel111";
}
3.ViewExcel
package net.spring.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;
public class ViewExcel extends AbstractExcelView {
@Override
protected void buildExcelDocument(Map<String, Object> map,
HSSFWorkbook workbook, HttpServletRequest arg2,
HttpServletResponse response) throws Exception {
String p1 = (String) map.get("p1");
String p2 = (String) map.get("p2");
// 设值文件名称:显示对话框提示用户下载或打开
response.setHeader("Content-Disposition", "attachment;filename="
+ new String("用户列表".getBytes(), "ISO-8859-1"));
// sheet的名称
HSSFSheet sheet = workbook.createSheet("testSheet");
HSSFRow row = null;
HSSFCell cell = null;
// 行号
int rowIndex = 0;
// 列号
int cellIndex = 0;
// 通过sheet对象添加一行
row = sheet.createRow(rowIndex++);
// 通过row对象添加一列
cell = row.createCell(cellIndex++);
// 设值列的内容
cell.setCellValue("第一列的内容");
// 添加一列
cell = row.createCell(cellIndex++);
// 设值列的内容
cell.setCellValue(p1);
// 列号清零
cellIndex = 0;
// 添加一行
row = sheet.createRow(rowIndex++);
// 添加一列
cell = row.createCell(cellIndex++);
// 设值列的内容
cell.setCellValue("第二列的内容");
// 添加一列
cell = row.createCell(cellIndex++);
// 设值列的内容
cell.setCellValue(p2);
}
}
效果图:
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/116699.html原文链接:https://javaforall.cn