您的位置:首页 > 编程语言 > Java开发

spring mvc 导出Excel

2015-09-11 16:24 639 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/sulaimanmakun/article/details/84741301 一、pom.xml引入jar包

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>


二、加入Excel工具类ExcelUtils.java

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

import javax.servlet.ServletOutputStream;

import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtil {

public static void exportExcel(List<Object> list,String sheetName, String[] titles, ServletOutputStream outputStream) {
// 创建一个workbook 对应一个excel应用文件
XSSFWorkbook workBook = new XSSFWorkbook();
// 在workbook中添加一个sheet,对应Excel文件中的sheet
XSSFSheet sheet = workBook.createSheet(sheetName);
XSSFCellStyle headStyle = getHeadStyle(workBook);
XSSFCellStyle bodyStyle = getBodyStyle(workBook);
// 构建表头
XSSFRow headRow = sheet.createRow(0);
XSSFCell cell = null;
for (int i = 0 ; i < titles.length; i++) {
cell = headRow.createCell(i);
cell.setCellStyle(headStyle);
cell.setCellValue(titles[i]);
}
// 构建表体数据
if (list != null && list.size() > 0) {
for (int j = 0 ; j < list.size() ; j++) {
XSSFRow bodyRow = sheet.createRow(j + 1);
Class<? extends Object> bean = list.get(j).getClass(); //获取对象
/*
* 得到类中的所有属性集合
*/
Field[] fs = bean.getDeclaredFields();
for (int i = 0 ; i < fs.length ; i++) {
Field field = fs[i];
field.setAccessible(true); //设置些属性是可以访问的
try {
cell = bodyRow.createCell(i);
cell.setCellStyle(bodyStyle);
cell.setCellValue((String)FieldsUtils.invokeMethod(list.get(j), field.getName()));//得到此属性的值
}catch (Exception e) {
}
}
}
}
try {
workBook.write(outputStream);
outputStream.flush();
outputStream.close();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
outputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}

}

/**
* 合并单元格后给合并后的单元格加边框
*
* @param region
* @param cs
*/
public static void setRegionStyle(CellRangeAddress region, XSSFCellStyle cs, XSSFSheet sheet) {

int toprowNum = region.getFirstRow();
for (int i = toprowNum ; i <= region.getLastRow() ; i++) {
XSSFRow row = sheet.getRow(i);
for (int j = region.getFirstColumn() ; j <= region.getLastColumn() ; j++) {
XSSFCell cell = row.getCell(j);
cell.setCellStyle(cs);
}
}
}

/**
* 设置表头的单元格样式
*
* @return
*/
public static XSSFCellStyle getHeadStyle(XSSFWorkbook wb) {
// 创建单元格样式
XSSFCellStyle cellStyle = wb.createCellStyle();
// 设置单元格的背景颜色为淡蓝色
cellStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
// 设置单元格居中对齐
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
// 设置单元格垂直居中对齐
cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
// 创建单元格内容显示不下时自动换行
cellStyle.setWrapText(true);
// 设置单元格字体样式
XSSFFont font = wb.createFont();
// 设置字体加粗
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("宋体");
font.setFontHeight((short) 200);
cellStyle.setFont(font);
// 设置单元格边框为细线条
cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
return cellStyle;
}

/**
* 设置表体的单元格样式
*
* @return
*/
public static XSSFCellStyle getBodyStyle(XSSFWorkbook wb) {
// 创建单元格样式
XSSFCellStyle cellStyle = wb.createCellStyle();
// 设置单元格居中对齐
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
// 设置单元格垂直居中对齐
cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
// 创建单元格内容显示不下时自动换行
cellStyle.setWrapText(true);
// 设置单元格字体样式
XSSFFont font = wb.createFont();
// 设置字体加粗
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("宋体");
font.setFontHeight((short) 100);
cellStyle.setFont(font);
// 设置单元格边框为细线条
cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
return cellStyle;
}
}


再加入FieldUtils.java,根据model中的列名获取对应的value

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


public class FieldsUtils {

/**
* @param object
* @return
* @throws SecurityException
* @throws IllegalArgumentException
* @throws NoSuchMethodException
* @throws IllegalAccessException
3ff7 * @throws InvocationTargetException
*/
public static Map<String, Object> getFileds(Object object) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Class<?> clazz = object.getClass();
Field[] fields = clazz.getDeclaredFields();
Map<String, Object> map = new HashMap<String, Object>();

for (int i = 0 ; i < fields.length ; i++) {
Object resultObject = invokeMethod(object, fields[i].getName());
map.put(fields[i].getName(), resultObject);
}

return map;
}

/**
* 根据列名获取值
*/
public static Object invokeMethod(Object owner, String fieldname){
Object object = null;
try {
Class<?> ownerClass = owner.getClass();
Method method = null;
method = ownerClass.getMethod("get" + captureName(fieldname));
object = method.invoke(owner);
}catch (Exception e) {
}
return object;
}

/**
* 首字母大写
* @param name
* @return
*/
public static String captureName(String name) {
// name = name.substring(0, 1).toUpperCase() + name.substring(1);
// return name;
char[] cs = name.toCharArray();
cs[0] -= 32;
return String.valueOf(cs);

}
}


Controller中对应的代码

/**
* excel导出
* @param request
* @return
* @throws IOException
*/
@RequestMapping(value = "/export.json")
public String export(HttpServletRequest request,HttpServletResponse response) throws IOException {
String fileName = new String(("Excel导出示例").getBytes(), "ISO8859_1");
response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");// 组装附件名称和格式
ServletOutputStream outputStream = response.getOutputStream();
String sheetName = "Excel导出示例列表";
List<Object> list = new ArrayList<Object>();
String[] titles = {"测试字段1","测试字段2","测试字段3".......};
ExcelEntity excelEntity = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for(Object bean : rows){
excelEntity = new ExcelEntity();
...
excelEntity.setCreateDate(dateFormat.format(bean.getCreateDate()));
list.add(excelEntity);
}
ExcelUtil.exportExcel(list,sheetName, titles, outputStream);
return null;
}



js中应该这样写


window.location.href="${path}/export.do";
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: