之前做的项目底层都已经封装好了,是以小编的导出做的很顺利,又一次做导出,感觉还是纪念一下占用我们这么多时间最后解决以及未解决的问题吧。实现思路相当简单,先从后台查询出数据,返回类型为list集合,然后设置表头,调用工具类,创建表,以上,即可。
【问题】
1、不能用AJAX调用后台的方法
绝对不能用AJAX方式调用,这样会不报错但是excel也不会传到浏览器,很是郁闷。因为AJAX的返回值类型是json,text,html,xml类型,或者可以说AJAX的接收类型只能是string字符串,不是流类型,所以无法实现文件下载。但用AJAX仍然可以获得文件内容,文件被保留在内存中,无法将文件保存到磁盘,这是因为JS无法和磁盘,进行交互,这也就是为什么代码不报错,而浏览器也不下载。解决方法是,用传统的方式提交,那就用location.href方式。可以是可以,但是问题又来了,在谷歌、火狐等优秀浏览器中尝试都没问题,但是IE却不成,直接报404错误,
IE6、7、8等都有这样相关的兼容性问题,IE9我没有尝试。各种的解决方式都试过之后,我终于放弃了,最后选择
了用form表单提交,也可以用iframe提交。代码如下:
// 导出全部
function exportAll() {
$('#exportall').form('submit', {
url : "transport/printCarReceiptUI.do"
});
}
2、导出内容中的时间
时间格式不对,Fri Nov 04 09:26:14 CST 2016,这样子的时间格式看着真是别扭,今天我还没解决,改日再更
新吧。
时间问题已解决。工具类中有个创建表格的方法,创建表格的时候需要将表头和字段进行比较,然后把对应的字段值
放到那一列中,这个时候加上一个获取数据类型并判断。具体代码如下(下面poi工具类的代码页已更新):
//获取返回类型
String returnType = method.getReturnType().getName();
String data = method.invoke(obj)==null?"":method.invoke(obj).toString();
Cell cell = dataRow.createCell(columnIndex);
if(data!=null&&!"".equals(data)){
if("int".equals(returnType)){
cell.setCellValue(Integer.parseInt(data));
}else if("long".equals(returnType)){
cell.setCellValue(Long.parseLong(data));
}else if("float".equals(returnType)){
cell.setCellValue(floatDecimalFormat.format(Float.parseFloat(data)));
}else if("double".equals(returnType)){
cell.setCellValue(doubleDecimalFormat.format(Double.parseDouble(data)));
}else if("java.util.Date".equals(returnType)){
Date date = parse(data, "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = format.format(date);
cell.setCellValue(strDate);
}else{
cell.setCellValue(data);
}
}
}else{ //字段为空 检查该列是否是公式
if(colFormula!=null){
String sixBuf = colFormula[columnIndex].replace("@", (rowIndex+1)+"");
Cell cell = dataRow.createCell(columnIndex);
cell.setCellFormula(sixBuf.toString());
}
}
********************************************实现代码篇******************************************************
下面再介绍两种实现方式,一种是引用poi的jar包,一种是引用jxl的jar包。
【poi工具类方式】
1.工具类代码
package com.greatwall.dcs.common.core.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
public class PoiExcelExport {
HttpServletResponse response;
// 文件名
private String fileName ;
//文件保存路径
private String fileDir;
//sheet名
private String sheetName;
//表头字体
private String titleFontType = "Arial Unicode MS";
//表头背景色
private String titleBackColor = "C1FBEE";
//表头字号
private short titleFontSize = 12;
//添加自动筛选的列 如 A:M
private String address = "";
//正文字体
private String contentFontType = "Arial Unicode MS";
//正文字号
private short contentFontSize = 12;
//Float类型数据小数位
private String floatDecimal = ".00";
//Double类型数据小数位
private String doubleDecimal = ".00";
//设置列的公式
private String colFormula[] = null;
DecimalFormat floatDecimalFormat=new DecimalFormat(floatDecimal);
DecimalFormat doubleDecimalFormat=new DecimalFormat(doubleDecimal);
DecimalFormat dateDecimalFormat=new DecimalFormat();
private HSSFWorkbook workbook = null;
public PoiExcelExport(String fileDir,String sheetName){
this.fileDir = fileDir;
this.sheetName = sheetName;
workbook = new HSSFWorkbook();
}
public PoiExcelExport(HttpServletResponse response,String fileName,String sheetName){
this.response = response;
this.sheetName = sheetName;
workbook = new HSSFWorkbook();
}
/**
* 设置表头字体.
* @param titleFontType
*/
public void setTitleFontType(String titleFontType) {
this.titleFontType = titleFontType;
}
/**
* 设置表头背景色.
* @param titleBackColor 十六进制
*/
public void setTitleBackColor(String titleBackColor) {
this.titleBackColor = titleBackColor;
}
/**
* 设置表头字体大小.
* @param titleFontSize
*/
public void setTitleFontSize(short titleFontSize) {
this.titleFontSize = titleFontSize;
}
/**
* 设置表头自动筛选栏位,如A:AC.
* @param address
*/
public void setAddress(String address) {
this.address = address;
}
/**
* 设置正文字体.
* @param contentFontType
*/
public void setContentFontType(String contentFontType) {
this.contentFontType = contentFontType;
}
/**
* 设置正文字号.
* @param contentFontSize
*/
public void setContentFontSize(short contentFontSize) {
this.contentFontSize = contentFontSize;
}
/**
* 设置float类型数据小数位 默认.00
* @param doubleDecimal 如 ".00"
*/
public void setDoubleDecimal(String doubleDecimal) {
this.doubleDecimal = doubleDecimal;
}
/**
* 设置doubel类型数据小数位 默认.00
* @param floatDecimalFormat 如 ".00
*/
public void setFloatDecimalFormat(DecimalFormat floatDecimalFormat) {
this.floatDecimalFormat = floatDecimalFormat;
}
/**
* 设置列的公式
* @param colFormula 存储i-1列的公式 涉及到的行号使用@替换 如A@+B@
*/
public void setColFormula(String[] colFormula) {
this.colFormula = colFormula;
}
/**
* 写excel.
* @param titleColumn 对应bean的属性名
* @param titleName excel要导出的表名
* @param titleSize 列宽
* @param dataList 数据
*/
public void wirteExcel(String titleColumn[],String titleName[],int titleSize[],List<?> dataList){
//添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
Sheet sheet = workbook.createSheet(this.sheetName);
//新建文件
OutputStream out = null;
try {
if(fileDir!=null){
//有文件路径
out = new FileOutputStream(fileDir);
}else{
//否则,直接写到输出流中
out = response.getOutputStream();
fileName = fileName+".xls";
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(fileName, "UTF-8"));
}
//写入excel的表头
Row titleNameRow = workbook.getSheet(sheetName).createRow(0);
//设置样式
HSSFCellStyle titleStyle = workbook.createCellStyle();
titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, titleFontType, (short) titleFontSize);
titleStyle = (HSSFCellStyle) setColor(titleStyle, titleBackColor, (short)10);
for(int i = 0;i < titleName.length;i++){
sheet.setColumnWidth(i, titleSize[i]*256); //设置宽度
Cell cell = titleNameRow.createCell(i);
cell.setCellStyle(titleStyle);
cell.setCellValue(titleName[i].toString());
}
//为表头添加自动筛选
if(!"".equals(address)){
CellRangeAddress c = (CellRangeAddress) CellRangeAddress.valueOf(address);
sheet.setAutoFilter(c);
}
//通过反射获取数据并写入到excel中
if(dataList!=null&&dataList.size()>0){
//设置样式
HSSFCellStyle dataStyle = workbook.createCellStyle();
titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, contentFontType, (short) contentFontSize);
if(titleColumn.length>0){
for(int rowIndex = 1;rowIndex<=dataList.size();rowIndex++){
Object obj = dataList.get(rowIndex-1); //获得该对象
Class clsss = obj.getClass(); //获得该对对象的class实例
Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);
for(int columnIndex = 0;columnIndex<titleColumn.length;columnIndex++){
String title = titleColumn[columnIndex].toString().trim();
if(!"".equals(title)){ //字段不为空
//使首字母大写
String UTitle = Character.toUpperCase(title.charAt(0))+ title.substring(1, title.length()); // 使其首字母大写;
String methodName = "get"+UTitle;
// 设置要执行的方法
Method method = clsss.getDeclaredMethod(methodName);
//获取返回类型
String returnType = method.getReturnType().getName();
String data = method.invoke(obj)==null?"":method.invoke(obj).toString();
Cell cell = dataRow.createCell(columnIndex);
if(data!=null&&!"".equals(data)){
if("int".equals(returnType)){
cell.setCellValue(Integer.parseInt(data));
}else if("long".equals(returnType)){
cell.setCellValue(Long.parseLong(data));
}else if("float".equals(returnType)){
cell.setCellValue(floatDecimalFormat.format(Float.parseFloat(data)));
}else if("double".equals(returnType)){
cell.setCellValue(doubleDecimalFormat.format(Double.parseDouble(data)));
}else if("java.util.Date".equals(returnType)){
Date date = parse(data, "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = format.format(date);
cell.setCellValue(strDate);
}else{
cell.setCellValue(data);
}
}
}else{ //字段为空 检查该列是否是公式
if(colFormula!=null){
String sixBuf = colFormula[columnIndex].replace("@", (rowIndex+1)+"");
Cell cell = dataRow.createCell(columnIndex);
cell.setCellFormula(sixBuf.toString());
}
}
}
}
}
}
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static Date parse(String str, String pattern, Locale locale) {
if (str == null || pattern == null) {
return null;
}
try {
return new SimpleDateFormat(pattern, locale).parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String format(Date date, String pattern, Locale locale) {
if (date == null || pattern == null) {
return null;
}
return new SimpleDateFormat(pattern, locale).format(date);
}
/**
* 将16进制的颜色代码写入样式中来设置颜色
* @param style 保证style统一
* @param color 颜色:66FFDD
* @param index 索引 8-64 使用时不可重复
* @return
*/
public CellStyle setColor(CellStyle style,String color,short index){
if(color!=""&&color!=null){
//转为RGB码
int r = Integer.parseInt((color.substring(0,2)),16); //转为16进制
int g = Integer.parseInt((color.substring(2,4)),16);
int b = Integer.parseInt((color.substring(4,6)),16);
//自定义cell颜色
HSSFPalette palette = workbook.getCustomPalette();
palette.setColorAtIndex((short)index, (byte) r, (byte) g, (byte) b);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(index);
}
return style;
}
/**
* 设置字体并加外边框
* @param style 样式
* @param style 字体名
* @param style 大小
* @return
*/
public CellStyle setFontAndBorder(CellStyle style,String fontName,short size){
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints(size);
font.setFontName(fontName);
font.setBold(true);
style.setFont(font);
style.setBorderBottom(CellStyle.BORDER_THIN); //下边框
style.setBorderLeft(CellStyle.BORDER_THIN);//左边框
style.setBorderTop(CellStyle.BORDER_THIN);//上边框
style.setBorderRight(CellStyle.BORDER_THIN);//右边框
return style;
}
/**
* 删除文件
* @param fileDir
* @return
*/
public boolean deleteExcel(){
boolean flag = false;
File file = new File(this.fileDir);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
file.delete();
flag = true;
}
}
return flag;
}
/**
* 删除文件
* @param fileDir
* @return
*/
public boolean deleteExcel(String path){
boolean flag = false;
File file = new File(path);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
file.delete();
flag = true;
}
}
return flag;
}
}
2.controller层的调用
// 导出excel
@SuppressWarnings("unchecked")
@RequestMapping("transport/exportExcel.do")
public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
// 1.获取要导出的数据
String searchCondition = request.getParameter("searchCondition");
String startDate = request.getParameter("startDate");
EasyUIDataGridResult result = new EasyUIDataGridResult();
if (StringUtil.isEmpty(searchCondition) && StringUtil.isEmpty(startDate)) {
result = queryAll(request, response);
} else {
result = queryByCondition(request, response);
}
List<VW_StockOutDetail> detailList = result.getRows();
// 2.创建Excel表头
PoiExcelExport pee = new PoiExcelExport(response, "", "出库");
String titleColumn[] = { "S_RShopName", "C_CarNo", "S_Type", "C_BottomNo", "C_EngineNo", "C_CarType",
"C_Pattern", "C_Configuration", "C_Color", "C_Accessory", "S_OrderID", "S_MadeTime", "D_AccountName",
"S_Address" };
String titleName[] = { "专营店名称", "车号", "类型", "底盘号", "发动机号", "车型", "款式", "配置", "颜色", "选装", "订单号", "出库时间", "资金账户",
"收车地址" };
int titleSize[] = { 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 };
boolean flag = true;
try {
// 调用工具类导出
pee.wirteExcel(titleColumn, titleName, titleSize, detailList);
System.out.println("导出成功");
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
}
【jxl工具类方式】
1.工具类代码
package com.greatwall.dcs.common.core.utils;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletResponse;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class ExcelUtil {
/**
* @MethodName : listToExcel
* @Description : 导出Excel(可以导出到本地文件系统,也可以导出到浏览器,可自定义工作表大小)
* @param list
* 数据源
* @param fieldMap
* 类的英文属性和Excel中的中文列名的对应关系 如果需要的是引用对象的属性,则英文属性使用类似于EL表达式的格式
* 如:list中存放的都是student,student中又有college属性,而我们需要学院名称,则可以这样写
* fieldMap.put("college.collegeName","学院名称")
* @param sheetName
* 工作表的名称
* @param sheetSize
* 每个工作表中记录的最大个数
* @param out
* 导出流
* @throws ExcelException
*/
public static <T> void listToExcel(List<T> list, LinkedHashMap<String, String> fieldMap, String sheetName,
int sheetSize, OutputStream out) throws ExcelException {
if (list.size() == 0 || list == null) {
throw new ExcelException("数据源中没有任何数据");
}
if (sheetSize > 65535 || sheetSize < 1) {
sheetSize = 65535;
}
// 创建工作簿并发送到OutputStream指定的地方
WritableWorkbook wwb;
try {
wwb = Workbook.createWorkbook(out);
// 因为2003的Excel一个工作表最多可以有65536条记录,除去列头剩下65535条
// 所以如果记录太多,需要放到多个工作表中,其实就是个分页的过程
// 1.计算一共有多少个工作表
double sheetNum = Math.ceil(list.size() / new Integer(sheetSize).doubleValue());
// 2.创建相应的工作表,并向其中填充数据
for (int i = 0; i < sheetNum; i++) {
// 如果只有一个工作表的情况
if (1 == sheetNum) {
WritableSheet sheet = wwb.createSheet(sheetName, i);
fillSheet(sheet, list, fieldMap, 0, list.size() - 1);
// 有多个工作表的情况
} else {
WritableSheet sheet = wwb.createSheet(sheetName + (i + 1), i);
// 获取开始索引和结束索引
int firstIndex = i * sheetSize;
int lastIndex = (i + 1) * sheetSize - 1 > list.size() - 1 ? list.size() - 1
: (i + 1) * sheetSize - 1;
// 填充工作表
fillSheet(sheet, list, fieldMap, firstIndex, lastIndex);
}
}
wwb.write();
wwb.close();
} catch (Exception e) {
e.printStackTrace();
// 如果是ExcelException,则直接抛出
if (e instanceof ExcelException) {
throw (ExcelException) e;
// 否则将其它异常包装成ExcelException再抛出
} else {
throw new ExcelException("导出Excel失败");
}
}
}
/**
* @MethodName : listToExcel
* @Description : 导出Excel(可以导出到本地文件系统,也可以导出到浏览器,工作表大小为2003支持的最大值)
* @param list
* 数据源
* @param fieldMap
* 类的英文属性和Excel中的中文列名的对应关系
* @param out
* 导出流
* @throws ExcelException
*/
public static <T> void listToExcel(List<T> list, LinkedHashMap<String, String> fieldMap, String sheetName,
OutputStream out) throws ExcelException {
listToExcel(list, fieldMap, sheetName, 65535, out);
}
/**
* @MethodName : listToExcel
* @Description : 导出Excel(导出到浏览器,可以自定义工作表的大小)
* @param list
* 数据源
* @param fieldMap
* 类的英文属性和Excel中的中文列名的对应关系
* @param sheetSize
* 每个工作表中记录的最大个数
* @param response
* 使用response可以导出到浏览器
* @throws ExcelException
*/
public static <T> void listToExcel(List<T> list, LinkedHashMap<String, String> fieldMap, String sheetName,
int sheetSize, HttpServletResponse response) throws ExcelException {
// 设置默认文件名为当前时间:年月日时分秒
String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
// 设置response头信息
response.reset();
response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
// 创建工作簿并发送到浏览器
try {
OutputStream out = response.getOutputStream();
listToExcel(list, fieldMap, sheetName, sheetSize, out);
} catch (Exception e) {
e.printStackTrace();
// 如果是ExcelException,则直接抛出
if (e instanceof ExcelException) {
throw (ExcelException) e;
// 否则将其它异常包装成ExcelException再抛出
} else {
throw new ExcelException("导出Excel失败");
}
}
}
/**
* @MethodName : listToExcel
* @Description : 导出Excel(导出到浏览器,工作表的大小是2003支持的最大值)
* @param list
* 数据源
* @param fieldMap
* 类的英文属性和Excel中的中文列名的对应关系
* @param response
* 使用response可以导出到浏览器
* @throws ExcelException
*/
public static <T> void listToExcel(List<T> list, LinkedHashMap<String, String> fieldMap, String sheetName,
HttpServletResponse response) throws ExcelException {
listToExcel(list, fieldMap, sheetName, 65535, response);
}
/**
* @MethodName : excelToList
* @Description : 将Excel转化为List
* @param in :承载着Excel的输入流
* @param sheetIndex :要导入的工作表序号
* @param entityClass :List中对象的类型(Excel中的每一行都要转化为该类型的对象)
* @param fieldMap :Excel中的中文列头和类的英文属性的对应关系Map
* @param uniqueFields :指定业务主键组合(即复合主键),这些列的组合不能重复
* @return :List
* @throws ExcelException
*/
public static <T> List<T> excelToList(
InputStream in,
String sheetName,
Class<T> entityClass,
LinkedHashMap<String, String> fieldMap,
String[] uniqueFields
) throws ExcelException{
//定义要返回的list
List<T> resultList=new ArrayList<T>();
try {
//根据Excel数据源创建WorkBook
Workbook wb=Workbook.getWorkbook(in);
//获取工作表
Sheet sheet=wb.getSheet(sheetName);
//获取工作表的有效行数
int realRows=0;
for(int i=0;i<sheet.getRows();i++){
int nullCols=0;
for(int j=0;j<sheet.getColumns();j++){
Cell currentCell=sheet.getCell(j,i);
if(currentCell==null || "".equals(currentCell.getContents().toString())){
nullCols++;
}
}
if(nullCols==sheet.getColumns()){
break;
}else{
realRows++;
}
}
//如果Excel中没有数据则提示错误
if(realRows<=1){
throw new ExcelException("Excel文件中没有任何数据");
}
Cell[] firstRow=sheet.getRow(0);
String[] excelFieldNames=new String[firstRow.length];
//获取Excel中的列名
for(int i=0;i<firstRow.length;i++){
excelFieldNames[i]=firstRow[i].getContents().toString().trim();
}
//判断需要的字段在Excel中是否都存在
boolean isExist=true;
List<String> excelFieldList=Arrays.asList(excelFieldNames);
for(String cnName : fieldMap.keySet()){
if(!excelFieldList.contains(cnName)){
isExist=false;
break;
}
}
//如果有列名不存在,则抛出异常,提示错误
if(!isExist){
throw new ExcelException("Excel中缺少必要的字段,或字段名称有误");
}
//将列名和列号放入Map中,这样通过列名就可以拿到列号
LinkedHashMap<String, Integer> colMap=new LinkedHashMap<String, Integer>();
for(int i=0;i<excelFieldNames.length;i++){
colMap.put(excelFieldNames[i], firstRow[i].getColumn());
}
//判断是否有重复行
//1.获取uniqueFields指定的列
Cell[][] uniqueCells=new Cell[uniqueFields.length][];
for(int i=0;i<uniqueFields.length;i++){
int col=colMap.get(uniqueFields[i]);
uniqueCells[i]=sheet.getColumn(col);
}
//2.从指定列中寻找重复行
for(int i=1;i<realRows;i++){
int nullCols=0;
for(int j=0;j<uniqueFields.length;j++){
String currentContent=uniqueCells[j][i].getContents();
Cell sameCell=sheet.findCell(currentContent,
uniqueCells[j][i].getColumn(),
uniqueCells[j][i].getRow()+1,
uniqueCells[j][i].getColumn(),
uniqueCells[j][realRows-1].getRow(),
true);
if(sameCell!=null){
nullCols++;
}
}
if(nullCols==uniqueFields.length){
throw new ExcelException("Excel中有重复行,请检查");
}
}
//将sheet转换为list
for(int i=1;i<realRows;i++){
//新建要转换的对象
T entity=entityClass.newInstance();
//给对象中的字段赋值
for(Entry<String, String> entry : fieldMap.entrySet()){
//获取中文字段名
String cnNormalName=entry.getKey();
//获取英文字段名
String enNormalName=entry.getValue();
//根据中文字段名获取列号
int col=colMap.get(cnNormalName);
//获取当前单元格中的内容
String content=sheet.getCell(col, i).getContents().toString().trim();
//给对象赋值
setFieldValueByName(enNormalName, content, entity);
}
resultList.add(entity);
}
} catch(Exception e){
e.printStackTrace();
//如果是ExcelException,则直接抛出
if(e instanceof ExcelException){
throw (ExcelException)e;
//否则将其它异常包装成ExcelException再抛出
}else{
e.printStackTrace();
throw new ExcelException("导入Excel失败");
}
}
return resultList;
}
/**
* @MethodName : getFieldValueByName
* @Description : 根据字段名获取字段值
* @param fieldName
* 字段名
* @param o
* 对象
* @return 字段值
*/
private static Object getFieldValueByName(String fieldName, Object o) throws Exception {
Object value = null;
Field field = getFieldByName(fieldName, o.getClass());
if (field != null) {
field.setAccessible(true);
value = field.get(o);
} else {
throw new ExcelException(o.getClass().getSimpleName() + "类不存在字段名 " + fieldName);
}
return value;
}
/**
* @MethodName : getFieldByName
* @Description : 根据字段名获取字段
* @param fieldName
* 字段名
* @param clazz
* 包含该字段的类
* @return 字段
*/
private static Field getFieldByName(String fieldName, Class<?> clazz) {
// 拿到本类的所有字段
Field[] selfFields = clazz.getDeclaredFields();
// 如果本类中存在该字段,则返回
for (Field field : selfFields) {
if (field.getName().equals(fieldName)) {
return field;
}
}
// 否则,查看父类中是否存在此字段,如果有则返回
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null && superClazz != Object.class) {
return getFieldByName(fieldName, superClazz);
}
// 如果本类和父类都没有,则返回空
return null;
}
/**
* @MethodName : getFieldValueByNameSequence
* @Description : 根据带路径或不带路径的属性名获取属性值
* 即接受简单属性名,如userName等,又接受带路径的属性名,如student.department.name等
*
* @param fieldNameSequence
* 带路径的属性名或简单属性名
* @param o
* 对象
* @return 属性值
* @throws Exception
*/
private static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception {
Object value = null;
// 将fieldNameSequence进行拆分
String[] attributes = fieldNameSequence.split("\\.");
if (attributes.length == 1) {
value = getFieldValueByName(fieldNameSequence, o);
} else {
// 根据属性名获取属性对象
Object fieldObj = getFieldValueByName(attributes[0], o);
String subFieldNameSequence = fieldNameSequence.substring(fieldNameSequence.indexOf(".") + 1);
value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
}
return value;
}
/**
* @MethodName : setFieldValueByName
* @Description : 根据字段名给对象的字段赋值
* @param fieldName
* 字段名
* @param fieldValue
* 字段值
* @param o
* 对象
*/
private static void setFieldValueByName(String fieldName, Object fieldValue, Object o) throws Exception {
Field field = getFieldByName(fieldName, o.getClass());
if (field != null) {
field.setAccessible(true);
// 获取字段类型
Class<?> fieldType = field.getType();
// 根据字段类型给字段赋值
if (String.class == fieldType) {
field.set(o, String.valueOf(fieldValue));
} else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
field.set(o, Integer.parseInt(fieldValue.toString()));
} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
field.set(o, Long.valueOf(fieldValue.toString()));
} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
field.set(o, Float.valueOf(fieldValue.toString()));
} else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {
field.set(o, Short.valueOf(fieldValue.toString()));
} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
field.set(o, Double.valueOf(fieldValue.toString()));
} else if (Character.TYPE == fieldType) {
if ((fieldValue != null) && (fieldValue.toString().length() > 0)) {
field.set(o, Character.valueOf(fieldValue.toString().charAt(0)));
}
} else if (Date.class == fieldType) {
field.set(o, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(fieldValue.toString()));
} else {
field.set(o, fieldValue);
}
} else {
throw new ExcelException(o.getClass().getSimpleName() + "类不存在字段名 " + fieldName);
}
}
/**
* @MethodName : setColumnAutoSize
* @Description : 设置工作表自动列宽和首行加粗
* @param ws
*/
private static void setColumnAutoSize(WritableSheet ws, int extraWith) {
// 获取本列的最宽单元格的宽度
for (int i = 0; i < ws.getColumns(); i++) {
int colWith = 0;
for (int j = 0; j < ws.getRows(); j++) {
String content = ws.getCell(i, j).getContents().toString();
int cellWith = content.length();
if (colWith < cellWith) {
colWith = cellWith;
}
}
// 设置单元格的宽度为最宽宽度+额外宽度
ws.setColumnView(i, colWith + extraWith);
}
}
/**
* @MethodName : fillSheet
* @Description : 向工作表中填充数据
* @param sheet
* 工作表
* @param list
* 数据源
* @param fieldMap
* 中英文字段对应关系的Map
* @param firstIndex
* 开始索引
* @param lastIndex
* 结束索引
*/
private static <T> void fillSheet(WritableSheet sheet, List<T> list, LinkedHashMap<String, String> fieldMap,
int firstIndex, int lastIndex) throws Exception {
// 定义存放英文字段名和中文字段名的数组
String[] enFields = new String[fieldMap.size()];
String[] cnFields = new String[fieldMap.size()];
// 填充数组
int count = 0;
for (Entry<String, String> entry : fieldMap.entrySet()) {
enFields[count] = entry.getKey();
cnFields[count] = entry.getValue();
count++;
}
// 填充表头
for (int i = 0; i < cnFields.length; i++) {
Label label = new Label(i, 0, cnFields[i]);
sheet.addCell(label);
}
// 填充内容
int rowNo = 1;
for (int index = firstIndex; index <= lastIndex; index++) {
// 获取单个对象
T item = list.get(index);
for (int i = 0; i < enFields.length; i++) {
Object objValue = getFieldValueByNameSequence(enFields[i], item);
String fieldValue = objValue == null ? "" : objValue.toString();
Label label = new Label(i, rowNo, fieldValue);
sheet.addCell(label);
}
rowNo++;
}
// 设置自动列宽
setColumnAutoSize(sheet, 5);
}
}
2.controller层的调用
// 导出excel
@SuppressWarnings("unchecked")
@RequestMapping("transport/exportExcel.do")
public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
// 1.获取要导出的数据
String searchCondition = request.getParameter("searchCondition");
String startDate = request.getParameter("startDate");
EasyUIDataGridResult result = new EasyUIDataGridResult();
if (StringUtil.isEmpty(searchCondition) && StringUtil.isEmpty(startDate)) {
result = queryAll(request, response);
} else {
result = queryByCondition(request, response);
}
List<VW_StockOutDetail> detailList = result.getRows();
// 2.创建Excel表头
LinkedHashMap<String, String> fieldMap = new LinkedHashMap<String, String>();
fieldMap.put("S_RShopName", "专营店名称");
fieldMap.put("C_CarNo", "车号");
fieldMap.put("S_Type", "类型");
fieldMap.put("C_BottomNo", "底盘号");
fieldMap.put("C_EngineNo", "发动机号");
fieldMap.put("C_CarType", "车型");
fieldMap.put("C_Pattern", "款式");
fieldMap.put("C_Configuration", "配置");
fieldMap.put("C_Color", "颜色");
fieldMap.put("C_Accessory", "选装");
fieldMap.put("S_OrderID", "订单号");
fieldMap.put("S_MadeTime", "出库时间");
fieldMap.put("D_AccountName", "资金账户");
fieldMap.put("S_Address", "收车地址");
String sheetName = "出库明细表";
boolean flag = true;
try {
// 调用工具类导出
ExcelUtil.listToExcel(detailList, fieldMap, sheetName, response);
System.out.println("导出成功");
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
}