分享一下我的偶像大神的人工智能教程!http://blog.csdn.net/jiangjunshow
也欢迎转载我的文章,转载请注明出处 https://blog.csdn.net/aabbyyz
java导出Excel的方法有多种,最为常用的方式就是使用第三方jar包,目前POI和JXL是最常用的二方包了,也推荐使用这两种。
POI这里不详细解释,可参考徐老师发的博客:http://blog.csdn.net/evangel_z/article/details/7332535,他利用开源组件POI3.0.2动态导出EXCEL文档的通用处理类ExportExcel,详细使用方法下载最新代码看看就可以里,徐老师写的很明了!总之思路就是用Servlet接受post、get请求,获取文件导出路径,然后将测试数据封装好调用通用处理类导出Excel,然后再下载刚导出的Excel,会自动在浏览器弹出选择保存路径的弹出框,这样就达到里大家常见的文件导出下载的功能!当然,真正的项目里不可能把文件导出到本地,肯定是先吧文件导出到服务器上,再去服务器下载,对于用户来说就感觉好像直接就导出了!
这种实现逻辑也可以修改,就是把通用处理类ExportExcel从void改为返回read好数据的InputStream,而不要直接就去write,然后调用下载的方法downLoad使用HttpServletResponse.getOutputStream()所得到的输出流来write数据,然后调用flush()时就会在页面弹出选择路径的弹出框,选择好后数据就真正从缓存输出到了Excel中,这样就省去里中间先要导出一次的步骤了。
我这里讲一下JXL,其实和POI差不多,就是调用的组件不同,引入的jar包不同了,整个Excel导出下载的逻辑还是一样的。好了,直接上代码,都是通用代码,以后都能用的上。
先是几个mode类封装了在处理过程中会用到的模型。
ExcelColMode 主要封装的是Map中的key或者dto中实现get方法的字段名,其实就是表格的标题的属性名。
public class ExcelColMode {
/**
* Map中的key或者dto中实现get方法的字段名
*/
private String name;
/** 列宽 */
private Integer width;
/**
* 字体格式,可以设置字体大小,字体颜色,字体加粗
*/
private ExcelFontFormat fontFormat;
/**
* 内容格式化
*/
private ExcelColModelFormatterInter contentFormatter;
public ExcelColMode(String name) {
this.name = name;
}
public ExcelColMode(String name, Integer width) {
this.name = name;
this.width = width;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ExcelFontFormat getFontFormat() {
return fontFormat;
}
public void setFontFormat(ExcelFontFormat fontFormat) {
this.fontFormat = fontFormat;
}
public ExcelColModelFormatterInter getContentFormatter() {
return contentFormatter;
}
public void setContentFormatter(ExcelColModelFormatterInter contentFormatter) {
this.contentFormatter = contentFormatter
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
}
ExcelHeadCell 主要封装的是标题名
public class ExcelHeadCell implements Comparable {
/**
* 列合并
*/
private int colSpan;
/**
* 展现字符内容
*/
private String content;
/**
* 父列的序列号
*/
private int fatherIndex;
/**
* 字体格式等
*/
private ExcelFontFormat fontFormat;
private Integer height;
/**
* 最基础的单元格,没有行合并和列合并
*
* @param content
*/
public ExcelHeadCell(String content) {
this.colSpan = 1;
this.content = content;
}
public ExcelHeadCell(String content, Integer height) {
this.colSpan = 1;
this.content = content;
this.height = height;
}
public ExcelHeadCell(String content, int fatherIndex, ExcelFontFormat fontFormat) {
this.colSpan = 1;
this.content = content;
this.fatherIndex = fatherIndex;
this.fontFormat = fontFormat;
}
public int getColSpan() {
return colSpan;
}
public void setColSpan(int colSpan) {
this.colSpan = colSpan;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public ExcelFontFormat getFontFormat() {
return fontFormat;
}
public void setFontFormat(ExcelFontFormat fontFormat) {
this.fontFormat = fontFormat;
}
public int getFatherIndex() {
return fatherIndex;
}
public void setFatherIndex(int fatherIndex) {
this.fatherIndex = fatherIndex;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public int compareTo(ExcelHeadCell o) {
int i = -1;
if (o == null) {
i = 1;
} else {
i = o.fatherIndex > this.fatherIndex ? -1 : 1;
if (o.fatherIndex == this.fatherIndex) {
i = 0;
}
}
return i;
}
}
ExcelExportRule 主要封装的是之前的ExcelColMode和ExcelHeadCell以及sheet页名称sheetName
public class ExcelExportRule {
/**
* 封装如何从数据集取数据,数据显示格式,日期格式和数字格式在这里设置
*/
private List colModes;
/**
* 封装EXCEL头部内容及内容显示格式
*/
private List> headCols;
/**
* 数据背景颜色区分,0:不区分,1:按行奇偶区分,奇数行白色,偶数行灰色,2:按列奇偶区分 奇数列白色,偶数列灰色,
* 注意:此参数为0时,单元格设置的背景色才起作用
*/
private int distinguishable = 0;
/**
* EXCEL的sheet页名称
*/
private String sheetName;
/**
* 是否树形结构,1:是,0:否
*/
private String hierarchical = "0";
/**
* id字段名,当hierarchical="1"时候才起作用
*/
private String idName;
/**
* 父id字段名,当hierarchical="1"时候才起作用
*/
private String pidName;
public List getColModes() {
return colModes;
}
public void setColModes(List colModes) {
this.colModes = colModes;
}
public List> getHeadCols() {
return headCols;
}
public void setHeadCols(List> headCols) {
this.headCols = headCols;
}
public int getDistinguishable() {
return distinguishable;
}
public void setDistinguishable(int distinguishable) {
this.distinguishable = distinguishable;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public String getHierarchical() {
return hierarchical;
}
public void setHierarchical(String hierarchical) {
this.hierarchical = hierarchical;
}
public String getIdName() {
return idName;
}
public void setIdName(String idName) {
this.idName = idName;
}
public String getPidName() {
return pidName;
}
public void setPidName(String pidName) {
this.pidName = pidName;
}
public void addExcelColMode(ExcelColMode excelColMode) {
if (colModes == null)
colModes = new ArrayList();
colModes.add(excelColMode);
}
public void addExcelHeadCellList(List list) {
if (headCols == null)
headCols = new ArrayList>();
headCols.add(list);
}
}
ExcelFontFormat 封装的是表格的一些样式,如果对此没什么要求可以忽略
public class ExcelFontFormat {
private int font = 0; // 字体 0:宋体,1:楷体,2:黑体,3:仿宋体,4:隶书
private Colour color = Colour.BLACK; // 字体颜色
private boolean bold = false; // 是否加粗
private int flow = 0; // 文字浮动方向,0:靠左(默认),1:居中,2:靠右,
private int fontSize = 0; // 文字大小,0:正常,-2,-1,0,1,2,3,4依次加大,最大到4
private Colour backgroundColor = Colour.WHITE; // 单元格填充色
private boolean italic;// 是否斜体
private int verticalAlign = 1; // 文字上下对齐 0:上 1:中 2:下
public int getFont() {
return font;
}
public void setFont(int font) {
this.font = font;
}
public Colour getColor() {
return color;
}
public void setColor(Colour color) {
this.color = color;
}
public Colour getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(Colour backgroundColor) {
this.backgroundColor = backgroundColor;
}
public boolean isBold() {
return bold;
}
public void setBold(boolean bold) {
this.bold = bold;
}
public int getFontSize() {
return fontSize;
}
public void setFontSize(int fontSize) {
this.fontSize = fontSize;
}
public int getFlow() {
return flow;
}
public void setFlow(int flow) {
this.flow = flow;
}
public Alignment convertFlow() {
return convertFlow(flow);
}
public static Alignment convertFlow(int flow) {
Alignment al = null;
switch (flow) {
case 0:
al = Alignment.LEFT;
break;
case 1:
al = Alignment.CENTRE;
break;
case 2:
al = Alignment.RIGHT;
break;
default:
al = Alignment.LEFT;
}
return al;
}
public FontName convertFontName() {
return convertFontName(font);
}
public static FontName convertFontName(int font) {
FontName fn = null;
switch (font) {
case 0:
fn = WritableFont.createFont("SimSun");
break;
case 1:
fn = WritableFont.createFont("KaiTi");
break;
case 2:
fn = WritableFont.createFont("SimHei");
break;
case 3:
fn = WritableFont.createFont("FangSong");
break;
case 4:
fn = WritableFont.createFont("LiSu");
break;
default:
fn = WritableFont.createFont("STSong");
}
return fn;
}
public int convertFontSize() {
return convertFontSize(fontSize);
}
public static int convertFontSize(int fontSize) {
return 12 + fontSize * 2;
}
@Override
public boolean equals(Object obj) {
boolean eq = false;
if (this == obj) {
eq = true;
} else if (obj != null && obj instanceof ExcelFontFormat) {
ExcelFontFormat e = (ExcelFontFormat) obj;
if (e.bold == this.bold && e.backgroundColor == this.backgroundColor && e.color == this.color
&& e.flow == this.flow && e.font == this.font && e.fontSize == this.fontSize
&& e.italic == this.italic) {
eq = true;
}
}
return eq;
}
public boolean isItalic() {
return italic;
}
public void setItalic(boolean italic) {
this.italic = italic;
}
public int getVerticalAlign() {
return verticalAlign;
}
public void setVerticalAlign(int verticalAlign) {
this.verticalAlign = verticalAlign;
}
}
4个mode类以及有了,我介绍的很简单,每个封装类其实还封装了一些其他的,但因为我的例子就只用到了这些就不多讲了。下面是Excel处理类ExcelHelper,代码比较多,其实大家不用管太多,粘贴过来用就行了,只要知道怎么用他(包括输入给些什么,输出的ByteArrayInputStream怎么用)就行。
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableFont.FontName;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.JxlWriteException;
import jxl.write.biff.RowsExceededException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.newsee.dto.common.ExcelColMode;
import com.newsee.dto.common.ExcelExportRule;
import com.newsee.dto.common.ExcelFontFormat;
import com.newsee.dto.common.ExcelHeadCell;
public class ExcelHelper {
private static Log log = LogFactory.getLog(ExcelHelper.class);
/**
* 实际需要展现的数据,支持DTO和Map
*/
private List
接下来是测试类。
public class TestExcelUtil {
@Test
public void test() throws Exception {
ExcelHelper excelHelper = new ExcelHelper();
List<Object> rowDatas = new ArrayList<Object>();
Map<String, String> map = new HashMap<String, String>();
map.put("userName", "张三");
map.put("sex", "男");
rowDatas.add(map);
Map<String, String> map1 = new HashMap<String, String>();
map1.put("userName", "李四");
map1.put("sex", "男");
rowDatas.add(map1);
List<ExcelHeadCell> headCells = new ArrayList<ExcelHeadCell>();
headCells.add(new ExcelHeadCell("姓名"));
headCells.add(new ExcelHeadCell("性别"));
List<List<ExcelHeadCell>> headCellsList = new ArrayList<List<ExcelHeadCell>>();
headCellsList.add(headCells);
ExcelExportRule rule = new ExcelExportRule();
rule.setSheetName("测试");
rule.setHeadCols(headCellsList);
List<ExcelColMode> colModes = new ArrayList<ExcelColMode>();
colModes.add(new ExcelColMode("userName"));
colModes.add(new ExcelColMode("sex"));
rule.setColModes(colModes);
InputStream inputStream = excelHelper.writeExcel(rowDatas, rule);
File file = new File("d:/test.xls");
if (file.exists())
file.delete();
file.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte b[] = new byte[512];
int i = inputStream.read(b);
while (i != -1) {
fileOutputStream.write(b);
i = inputStream.read(b);
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
}
}
通过看测试类应该就知道使用方法了吧,最后再给一个实际的从页面到后台的例子:从页面发来的一个请求,包含了表格的标题、内容、sheet名、Excel名,然后实现生成并下载Excel(在页面会弹出选择保存路径框)的过程。
首先是页面:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>导出Exceltitle>
<script src="../../../ns-face-sys/common/lib/jquery-1.11.2.min.js">script>
<script src="../../../ns-face-sys/common/js/newsee.js">script>
<script src="../../../ns-face-sys/common/js/newsee.ui.js">script>
head>
<body>
<form id="formid" name= "myform" method = "post" action = "/ns-face-sys/rest/system/export/excel">
<input id="headCells" name="headCells" value="" type="hidden"/>
<input id="rowDatas" name="rowDatas" value="" type="hidden"/>
<input id="sheetName" name="sheetName" value="人员信息" type="hidden"/>
<input id="excelName" name="excelName" value="人员信息表" type="hidden"/>
<table id="table">
<tr>
<td>序号td>
<td>姓名td>
<td>备注td>
tr>
<tr>
<td>1td>
<td>yjctd>
<td>欣lptd>
tr>
<tr>
<td>2td>
<td>lsxtd>
<td>诚lgtd>
tr>
<tr>
<td>3td>
<td>测试1td>
<td>备注1td>
tr>
<tr>
<td>4td>
<td>测试2td>
<td>备注2td>
tr>
table>
<input id="export" type="button" value="导出Excel" onclick="exportExcel()"/>
form>
<script type="text/javascript" src="export_excel.js">script>
body>
html>
然后是js,里面做了把表格数据整合成后台需要的数据(每列数据用”,”隔开,每行数据用”;”隔开,标题和内容分别放在隐藏的input里传给后台解析),放到隐藏域里,然后以提交表单的形式发送到后台。
千万注意:不要使用ajax请求,虽然也能发到后台,但会导致浏览器收不到response,导致弹不出选择保存路径的弹出框了!!!
function exportExcel(){
document.charset='utf-8';
var head = getHead();
var data = getData();
// var path = getPath();
$("#headCells").val(head);
$("#rowDatas").val(data);
$("#formid").submit();
// var postData = [{
// Request: {
// Data: {
// headCells : head,
// rowDatas : data,
// sheetName : "人员信息",
// path : path,
// excelName : "人员信息表"
// }
// }
// }]
// $.ajax({
// url: "/ns-face-sys/rest/system/export/excel",
// type: "post",
// dataType: 'json',
// async: true,
// data: {
// request: newsee.base.JsonArrayToStringCfz(postData)
// }
// });
function getHead(){
var head = "";
var uls = $("#table").find("tr");
var lis = $(uls[0]).children("td");
for(var j=0;jif(j == lis.length-1){
head += $(lis[j]).text();
}else{
head += $(lis[j]).text() + ",";
}
}
return head;
}
function getData(){
var data = "";
var uls = $("#table").find("tr");
for(var i=1;ivar lis = $(uls[i]).children("td");
for(var j=0;jif(j == lis.length-1 && i == uls.length-1){
data += $(lis[j]).text();
}else if(j == lis.length-1 && i != uls.length-1){
data += $(lis[j]).text() + ";";
}else{
data += $(lis[j]).text() + ",";
}
}
}
return data;
}
function getPath(){
return "D:";
}
然后时控制器层代码,里面为了解决页面过来的数据有中文乱码,采用了笨方法,一个一个指定解码方式
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import org.springframework.stereotype.Controller;
import com.newsee.face.common.ExportExcel;
@Path("system")
@Controller
public class SystemExcelFace {
/**
* 导出excel入口
* @param request
* @param response
* @throws Exception
*/
@POST
@Path("/export/excel")
public void showImg(@FormParam("headCells") String headCells,
@FormParam("rowDatas") String rowDatas,
@FormParam("sheetName") String sheetName,
@FormParam("excelName") String excelName,
@Context HttpServletResponse response) throws Exception {
headCells=new String(headCells.getBytes("iso-8859-1"),"UTF-8");
rowDatas=new String(rowDatas.getBytes("iso-8859-1"),"UTF-8");
sheetName=new String(sheetName.getBytes("iso-8859-1"),"UTF-8");
excelName=new String(excelName.getBytes("iso-8859-1"),"UTF-8");
new ExportExcel().exportExcel(rowDatas, headCells, sheetName, excelName,response);
}
}
然后就是业务逻辑层了ExportExcel,这里就调用了之前介绍的导出Excel处理类ExcelHelper。
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.newsee.dto.common.ExcelColMode;
import com.newsee.dto.common.ExcelExportRule;
import com.newsee.dto.common.ExcelHeadCell;
import com.newsee.util.ExcelHelper;
import com.newsee.util.StringUtil;
/**
* 导出excel
*
* @author yaojiacheng
*
*/
public class ExportExcel {
/**
* 导出excel
*
* @param requestContent
* @return
*/
public void exportExcel(String rowData,String headCell,String sheetName,String excelName, HttpServletResponse response) throws Exception {
if (StringUtil.isAnyBlank(rowData, headCell)) {
return;
}
if(response == null){
return;
}
ExcelHelper excelHelper = new ExcelHelper();
List headCells = new ArrayList();
String[] headCellsArray = headCell.split(",");
for (String hc : headCellsArray) {
headCells.add(new ExcelHeadCell(hc));
}
List> headCellsList = new ArrayList>();
headCellsList.add(headCells);
ExcelExportRule rule = new ExcelExportRule();
if (StringUtil.isBlank(sheetName)) {
rule.setSheetName("测试");
} else {
rule.setSheetName(sheetName);
}
rule.setHeadCols(headCellsList);
List colModes = new ArrayList();
for (int i = 0; i < headCellsArray.length; i++) {
colModes.add(new ExcelColMode(i + ""));
}
rule.setColModes(colModes);
List rowDatas = new ArrayList();
String[] rowDataArrays = rowData.split(";");
for (String rowDataArray : rowDataArrays) {
Map map = new HashMap();
String[] rowDataAs = rowDataArray.split(",");
for (int i = 0; i < rowDataAs.length; i++) {
map.put(i + "", rowDataAs[i]);
}
rowDatas.add(map);
}
InputStream fis = excelHelper.writeExcel(rowDatas, rule);
byte b[] = new byte[512];
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" +
URLEncoder.encode(excelName, "UTF-8")+ ".xls");
response.addHeader("Content-Length", "" + fis.available());
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=gb2312");
int i = fis.read(b);
while (i != -1) {
toClient.write(b);
i = fis.read(b);
}
toClient.flush();
toClient.close();
fis.close();
}
}
如上,使用response.getOutputStream()得到的输出流来write数据后会先放在缓存中,到执行toClient.flush()就会在页面弹出选择保存路径的选择框,点击保存后就下载成功了。这里没有Excel导出的过程,直接将经过Excel处理类得到的InputStream拿过来读取,然后写进OutputStream下载,通常这是最优的方式。
以上代码没有添加合并单元格的功能,需要合并单元格的同学们,可以自行修改代码,合并调用的方法就是:WritableSheet.mergeCells(int m,int n,int p,int q); 作用是从(m,n)到(p,q)的单元格全部合并,比如:
//合并第一列第二行到第六列第二行的所有单元格
sheet.mergeCells(0,1,5,1); //注意了m和p指的是列,n和q指的是行
可以在workbook.write();workbook.close();之前调用即可!
还需要注意的是,合并的单元格显示的内容是第一个单元格的内容,不是所有单元格的内容追加!
给我偶像的人工智能教程打call!http://blog.csdn.net/jiangjunshow