java excel导出下载_Java导出excel并下载功能
我们使用的导出并下载功能是利用一个插件叫POI的插件提供的导出功能,很实用;首先先导入Jar包:
Action代码:
public void exportToExcel(List data) throws Exception
{
this.setEnableAccessRequest(true);
this.setEnableAccessResponse(true);
HttpServletRequest request = this.getRequest();
HttpServletResponse response = this.getResponse();
String randomNumber = request.getParameter("randomNumber");// session名称
try {
session = request.getSession();
session.setAttribute(randomNumber, new Double(1));
// 导出的EXCEL文件名
String exportFileName = "addressBook.xlsx";
response.reset();
response.setContentType("octets/stream");
// response.setHeader("Content-Disposition","attachment;filename="+exportFileName);
response.setHeader("Content-Disposition", "attachment;filename=\"" + new String(exportFileName.getBytes("UTF-8"), "iso8859-1") + "\"");
// 导出的EXCEL列属性
List columnListName = new ArrayList();
columnListName.add("userName&姓名");
columnListName.add("mobile&手机");
columnListName.add("shopTel&分店电话");
columnListName.add("postName&职位");
columnListName.add("email&邮箱");
columnListName.add("shopAddress&分店地址");
Bean2ExcelConversionUtils.beans2excelFile07(columnListName, data, response.getOutputStream());
session.setAttribute(randomNumber, new Double(100));
} catch (Exception e) {
e.printStackTrace();
session.setAttribute(randomNumber, new Double(100));
} catch (Throwable e) {
e.printStackTrace();
session.setAttribute(randomNumber, new Double(100));
}
}
JSP代码:
function exportToExcel() {
var randomNumber=new Date().getTime();
top.$.jBox.tip("正在导出...", 'loading');
var exportDate = "${ctx}/xxxAction.do?method=export&randomNumber="+randomNumber;
$("#exportForm").attr("action", exportDate);
$("#exportForm").attr("method","post");
$("#exportForm").submit();
}
因为是使用的插件,所以需要引入一个工具类(下面的工具类直接复制到新建的类文件里面即可)
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
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.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.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
/**
* @author Tan Jiangyong
* @date 2013-9-3 下午3:36:43
* @version V1.0
*/
@SuppressWarnings("all")
public class Bean2ExcelConversionUtils {
private static final String PATTERN="yyyy-MM-dd HH:mm:ss"; //excel日期格式,默认配置
private static final String DATE_PATTERN="yyyy-MM-dd"; //excel日期格式
private static final String DATE_HH_PATTERN="HH:mm:ss"; //excel时间格式
private static final int TOTAL_SIZE=40000; //每个excel写入多少数据(默认配置)
private static final int MAX_SHEET_SIZE=10000; //每一个sheet的大小(默认配置)
private static final int COLUMN_WIDTH_WORD=25; //列宽,默认汉字个数为25个
private static final int FLUSH_ROWS=100; //每生成excel行数,内存中缓存记录数清空(目的,避免零时文件过大)
/**
* 07、10办公版EXCEL导出(数据直接写到服务器的EXCEL里,以下载的形式,下载导出的数据)
* @param listName 列表头名称
* @param beans 实体集合
* @param result 数字字典Map集
* @param filePath 服务器存放文件路径
* @param fileName 文件名称
* @param totalSize EXCEL条数量
* @param maxSheetSize sheet页条数量
* @return 文件集合
* @throws Exception
*/
public static List beans2excelFile07(List listName,List beans,HashMap> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{
if(totalSize==null || totalSize<=0)
totalSize=TOTAL_SIZE;
if(maxSheetSize==null || maxSheetSize<=0)
maxSheetSize=MAX_SHEET_SIZE;
if(fileName==null)
fileName="";
return beans2excelFile2007(listName, beans, result, filePath, fileName,totalSize,maxSheetSize);
}
/**
* 07、10办公版EXCEL导出(数据直接写到服务器的EXCEL里,以下载的形式,下载导出的数据)
* @param listName 列表头名称
* @param beans 实体集合
* @param result 数字字典Map集
* @param filePath 服务器存放文件路径
* @param fileName 文件名称
* @param totalSize EXCEL条数量
* @param maxSheetSize sheet页条数量
* @param request 客户端请求对象
* @param response 客户端响应对象
* @throws Exception
*/
public static void beans2excelFile07(List listName,List beans,HashMap> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize,HttpServletRequest request,HttpServletResponse response) throws Exception{
if(totalSize==null || totalSize<=0)
totalSize=TOTAL_SIZE;
if(maxSheetSize==null || maxSheetSize<=0)
maxSheetSize=MAX_SHEET_SIZE;
if(fileName==null)
fileName="";
List files = beans2excelFile2007(listName, beans, result, filePath, fileName,totalSize,maxSheetSize);
DownLoadUtils.downLoadFiles(files, filePath, request, response);
}
/**
* 07、10办公版EXCEL导出,每个EXCEL组织数据
* @param listName 列表头名称
* @param beans 实体集合
* @param result 数字字典Map集
* @param filePath 服务器存放文件路径
* @param fileName 文件名称
* @param totalSize EXCEL条数量
* @param maxSheetSize sheet页条数量
* @return 文件集合
* @throws Exception
*/
private static List beans2excelFile2007(List listName,List beans,HashMap> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{
if ((listName == null) || (listName.size() == 0)) {
throw new Exception("listName is null when create excel document");
}
List listFile=new ArrayList();//返回的文件集合
int size=beans==null?0:beans.size();
String fileSuffixName=".xlsx";//后缀
String path="";//文件路径
Integer startIdx=0;//数据读取的起始行
Integer endIdx=0;//数据读取的结束行
(new File(filePath)).mkdirs(); //没有该目录创建目录
if(size==0){
startIdx=0;
endIdx=(totalSize)>size?size:(totalSize);
String name=fileName+"_第0-0条数据";
path=filePath+File.separatorChar+name+fileSuffixName;
Workbook wb =new SXSSFWorkbook();
buildExcelDocument2007(wb, listName, beans,result,startIdx,endIdx,maxSheetSize);
//没有文件,创建文件
File file = new File(path);
if (!file.exists()){
file.createNewFile();
}
FileOutputStream out=new FileOutputStream(file);
wb.write(out);
out.close();
return listFile;
}
for (int i = 0; i < size;i++) {
int remainder=i%totalSize;
if(size==0 || remainder==0){
startIdx=i;
endIdx=(i+totalSize)>size?size:(i+totalSize);
String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"条数据";
path=filePath+"/"+name+fileSuffixName;
Workbook wb =new SXSSFWorkbook();
buildExcelDocument2007(wb, listName, beans,result,startIdx,endIdx,maxSheetSize);
//没有文件,创建文件
File file = new File(path);
if (!file.exists()){
file.createNewFile();
}
FileOutputStream out=new FileOutputStream(file);
wb.write(out);
out.close();
listFile.add(file);
}else if((size-i)endIdx){//最后,不满一万条
startIdx=i;
endIdx=i+totalSize;
String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"条数据";
path=filePath+name+"."+fileSuffixName;//没有文件,创建文件
Workbook wb =new SXSSFWorkbook();
buildExcelDocument2007(wb, listName, beans, result,startIdx,endIdx,maxSheetSize);
//没有文件,创建文件
File file = new File(path);
if (!file.exists()){
file.createNewFile();
}
FileOutputStream out=new FileOutputStream(file);
wb.write(out);
out.close();
listFile.add(file);
}
}
return listFile;
}
/**
* 07、10办公版EXCEL导出,每个EXCEL写入数据
* @param wb EXCEL工作薄
* @param listName 列表头名称
* @param beans 实体集合
* @param result 数字字典Map集
* @param startIdx 数据集合,开始行
* @param endIdx 数据集合,结束始行
* @param maxSheetSize SHEET页条数
* @throws Exception
*/
private static void buildExcelDocument2007(Workbook wb, List listName, List beans,HashMap> result,Integer startIdx,Integer endIdx,Integer maxSheetSize) throws Exception
{
int totalSize=endIdx-startIdx;//总共条数
try
{
CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);
List titles = new ArrayList();
List beanAttrNames = new ArrayList();
boolean flagListExists=false;
List flagList=new ArrayList();
List widthList=new ArrayList();
HashMap dateMap=new HashMap();
String[] header = new String[listName.size()];
int rows_max = 0;//标题占多少列
for (int i=0;i
{
String[] str=listName.get(i).split("&");
String en_name=str[0];
String zh_name=str[1];
beanAttrNames.add(i,en_name);
titles.add(i, zh_name);
header[i]=zh_name;
if (zh_name.split("_").length > rows_max) {
rows_max = zh_name.split("_").length;
}
if(str.length>2){
String flag=str[2];
flagList.add(i,flag);
if(!flagListExists)
flagListExists=true;
}
if(str.length>3){
widthList.add(str[3]);
}
if(str.length>4){
dateMap.put(en_name, str[4]);
}
}
PropertyDescriptor[] props = null;
int size=endIdx-startIdx;
Sheet sheet=null;
//如果没有数据,导出表头
if(size==0){
sheet=ExcelHeadUtils.getExcelHead2007(wb, header, "Sheet1");
sheet.setDefaultRowHeight((short)350);//高度
setColumnWidth2007(widthList, sheet,beanAttrNames.size());
return ;
}
int u=1;//用来创建每个sheet的行
int h=0;//用来标注每个sheet也得名字:多少行-多少行
for (int i = startIdx; i < endIdx ; i++) {
int remainder=h%maxSheetSize;
if(size==0 || i==startIdx || remainder==0){
u=1;
int section=(h+maxSheetSize)>totalSize?totalSize:(h+maxSheetSize);
sheet=ExcelHeadUtils.getExcelHead2007(wb, header,"第"+(h+1)+"-"+section+"条");
sheet.createFreezePane( 1, rows_max, 1, rows_max);
sheet.setDefaultRowHeight((short)350);//高度
setColumnWidth2007(widthList, sheet,beanAttrNames.size());
}
if(props==null)
props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();
Object bean = beans.get(i);
Row row = sheet.createRow(u+rows_max-1);
u++;
h++;
for (int j = 0; j < beanAttrNames.size(); j++) {
String beanAttrName = (String)beanAttrNames.get(j);
String flag="";
if(flagListExists)
flag=(String)flagList.get(j);
for (int k = 0; k < props.length; k++) {
String propName = props[k].getName();
if (propName.equals(beanAttrName))
{
String pattern=dateMap.get(beanAttrName);
Cell cell = row.createCell((short)j);
Object cellValue = callGetter(bean, props[k],pattern);
if("true".equalsIgnoreCase(flag)){
if(result!=null){
HashMap hash=result.get(beanAttrName);
if(hash!=null)
cellValue=hash.get(cellValue);
}
}
if (cellValue == null) {
cellValue = "";
}
setExcelCellText2007(cell, cellValue.toString(),cellStyle);
}
}
}
//每当行数达到设置的值就刷新数据到硬盘,以清理内存
if(i%FLUSH_ROWS==0){
((SXSSFSheet)sheet).flushRows();
}
}
} catch (Exception e) {
throw new Exception(e);
}
}
/**
* 07、10办公版EXCEL导出(直接以流的方式,写到客户端,导出的EXCEL文件只有一个)
* @param listName 列表头名称
* @param beans 实体集合
* @param maxSheetSize SHEET页的条数
* @param outputStream 客户端输出流
* @throws Exception
*/
public static void beans2excelFile07(List listName,List beans, OutputStream outputStream) throws Exception{
if ((listName == null) || (listName.size() == 0)) {
throw new Exception("listName is null when create excel document");
}
if (outputStream == null) {
throw new Exception("outputStream is null when create excel document");
}
Workbook wb =new SXSSFWorkbook();
beans2excelFile07(listName, beans, null, null, MAX_SHEET_SIZE, outputStream);
try {
wb.write(outputStream);
outputStream.close();
} catch (IOException e) {
throw new Exception(e);
}
}
/**
* 07、10办公版EXCEL导出(直接以流的方式,写到客户端,导出的EXCEL文件只有一个)
* @param listName 列表头名称
* @param beans 实体集合
* @param maxSheetSize SHEET页的条数
* @param outputStream 客户端输出流
* @throws Exception
*/
public static void beans2excelFile07(List listName,List beans,HashMap> result,String sheetName,Integer maxSheetSize, OutputStream outputStream) throws Exception{
if ((listName == null) || (listName.size() == 0)) {
throw new Exception("listName is null when create excel document");
}
if (outputStream == null) {
throw new Exception("outputStream is null when create excel document");
}
if(maxSheetSize==null || maxSheetSize<=0){
maxSheetSize=MAX_SHEET_SIZE;
}
if(sheetName==null || "".equals(sheetName.trim())){
sheetName="Sheet";
}
Workbook wb =new SXSSFWorkbook();
if(maxSheetSize==null || maxSheetSize<=0){
maxSheetSize=MAX_SHEET_SIZE;
}
buildExcelDocument2007(wb, listName, beans,result,sheetName,maxSheetSize);
try {
wb.write(outputStream);
outputStream.close();
} catch (IOException e) {
throw new Exception(e);
}
}
/**
*
* @param listName
* @param beans
* @param response
* @param fileName 导出的文件名称
* @throws Exception
*/
public static void beans2excelFile07(List listName, List beans, HttpServletResponse response,String fileName) throws Exception {
response.reset();
response.setContentType("octets/stream");
response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode(fileName, "UTF-8"));
if ((listName == null) || (listName.size() == 0)) {
throw new Exception("listName is null when create excel document");
}
if (response.getOutputStream() == null) {
throw new Exception("outputStream is null when create excel document");
}
beans2excelFile07(listName, beans, null, null, MAX_SHEET_SIZE, response.getOutputStream());
}
/**
* 07、10办公版EXCEL导出,EXCEL写入数据
* @param wb EXCEL工作薄
* @param listName 列表头名称
* @param beans 实体集合
* @param maxSheetSize SHEET页的条数
* @throws Exception
*/
private static void buildExcelDocument2007(Workbook wb, List listName, List beans,HashMap> result,String sheetName,Integer maxSheetSize) throws Exception
{
try
{
CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);
List titles = new ArrayList();
List beanAttrNames = new ArrayList();
List widthList = new ArrayList();
HashMap dateMap=new HashMap();
String[] header = new String[listName.size()];
int rows_max = 0;//标题占多少列
List flagList=new ArrayList();
boolean flagListExists=false;
for (int i=0;i
{
String[] str=listName.get(i).split("&");
String en_name=str[0];
String zh_name=str[1];
beanAttrNames.add(i,en_name);
titles.add(i, zh_name);
header[i]=zh_name;
if (zh_name.split("_").length > rows_max) {
rows_max = zh_name.split("_").length;
}
if(str.length>2){
String flag=str[2];
flagList.add(i,flag);
if(!flagListExists)
flagListExists=true;
}
if(str.length>3){
widthList.add(str[3]);
}
if(str.length>4){
dateMap.put(en_name, str[4]);
}
}
PropertyDescriptor[] props = null;
int size=beans==null?0:beans.size();
Sheet sheet=null;
//如果没有数据,导出表头
if(size==0){
sheet=ExcelHeadUtils.getExcelHead2007(wb, header, sheetName);
sheet.setDefaultRowHeight((short)350);//高度
setColumnWidth2007(widthList, sheet,beanAttrNames.size());
return ;
}
for (int i = 0; i < size ; i++) {
int remainder=i%maxSheetSize;
if(size==0 || i==0 || remainder==0){
sheet=ExcelHeadUtils.getExcelHead2007(wb, header,sheetName+(i/maxSheetSize));
sheet.createFreezePane( 1, rows_max, 1, rows_max);
sheet.setDefaultRowHeight((short)350);//高度
setColumnWidth2007(widthList, sheet,beanAttrNames.size());
}
if(props==null)
props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();
Object bean = beans.get(i);
Row row = sheet.createRow(remainder+rows_max);
for (int j = 0; j < beanAttrNames.size(); j++) {
String beanAttrName = (String)beanAttrNames.get(j);
String flag="";
if(flagListExists)
flag=(String)flagList.get(j);
for (int k = 0; k < props.length; k++) {
String propName = props[k].getName();
if (propName.equals(beanAttrName))
{
String pattern=dateMap.get(beanAttrName);
Cell cell = row.createCell((short)j);
Object cellValue = callGetter(bean, props[k],pattern);
if("true".equalsIgnoreCase(flag)){
if(result!=null){
HashMap hash=result.get(beanAttrName);
if(hash!=null)
cellValue=hash.get(cellValue);
}
}
if (cellValue == null) {
cellValue = "";
}
setExcelCellText2007(cell, cellValue.toString(),cellStyle);
}
}
}
//每当行数达到设置的值就刷新数据到硬盘,以清理内存
if(i%FLUSH_ROWS==0){
((SXSSFSheet)sheet).flushRows();
}
}
} catch (Exception e) {
throw new Exception(e);
}
}
/**
* 07、10办公版EXCEL导出(直接以流的方式,写到客户端,导出的EXCEL文件只有一个)
* @param listName 列表头名称
* @param beans 实体集合
* @param maxSheetSize SHEET页的条数
* @param outputStream 客户端输出流
* @throws Exception
*/
public static void beans2excelFile07List(List> listColumnName,List list2beans,HashMap>> result,List listSheetName, OutputStream outputStream) throws Exception{
if ((listColumnName == null) || (listColumnName.size() == 0)) {
throw new Exception("listColumnName is null when create excel document");
}
if (list2beans.size() != listColumnName.size()) {
throw new Exception("list2beans and listColumnName size Unequal");
}
if (outputStream == null) {
throw new Exception("outputStream is null when create excel document");
}
Workbook wb =new SXSSFWorkbook();
buildExcelDocument2007List(wb, listColumnName, list2beans, result, listSheetName);
try {
wb.write(outputStream);
outputStream.close();
} catch (IOException e) {
throw new Exception(e);
}
}
/**
* 07、10办公版EXCEL导出,EXCEL写入数据
* @param wb EXCEL工作薄
* @param listName 列表头名称
* @param beans 实体集合
* @param maxSheetSize SHEET页的条数
* @throws Exception
*/
private static void buildExcelDocument2007List(Workbook wb, List> listColumnName,List list2beans,HashMap>> resultMap,List listSheetName) throws Exception
{
try
{
int sheets=listColumnName.size();
boolean sheetNameIsNullFlag=false;
if(listSheetName==null || listSheetName.size()!=sheets){
sheetNameIsNullFlag=true;
}
for (int s = 0; s < sheets; s++) {
String sheetName="Sheet"+s;
if(!sheetNameIsNullFlag){
sheetName=listSheetName.get(s);
}
List listName=listColumnName.get(s);
CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);
List titles = new ArrayList();
List beanAttrNames = new ArrayList();
List widthList = new ArrayList();
HashMap dateMap=new HashMap();
String[] header = new String[listName.size()];
int rows_max = 0;//标题占多少列
List flagList=new ArrayList();
boolean flagListExists=false;
for (int i=0;i
{
String[] str=listName.get(i).split("&");
String en_name=str[0];
String zh_name=str[1];
beanAttrNames.add(i,en_name);
titles.add(i, zh_name);
header[i]=zh_name;
if (zh_name.split("_").length > rows_max) {
rows_max = zh_name.split("_").length;
}
if(str.length>2){
String flag=str[2];
flagList.add(i,flag);
if(!flagListExists)
flagListExists=true;
}
if(str.length>3){
widthList.add(str[3]);
}
if(str.length>4){
dateMap.put(en_name, str[4]);
}
}
PropertyDescriptor[] props = null;
ArrayList beans=(ArrayList)list2beans.get(s);
int size=beans==null?0:beans.size();
Sheet sheet=null;
//如果没有数据,导出表头
if(size==0){
sheet=ExcelHeadUtils.getExcelHead2007(wb, header, sheetName);
sheet.setDefaultRowHeight((short)350);//高度
setColumnWidth2007(widthList, sheet,beanAttrNames.size());
return ;
}
HashMap> result=null;
if(resultMap!=null){
result=resultMap.get(sheetName);
}
sheet=ExcelHeadUtils.getExcelHead2007(wb, header,sheetName);
sheet.createFreezePane( 1, rows_max, 1, rows_max);
sheet.setDefaultRowHeight((short)350);//高度
setColumnWidth2007(widthList, sheet,beanAttrNames.size());
for (int i = 0; i < size ; i++) {
if(props==null)
props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();
Object bean = beans.get(i);
Row row = sheet.createRow(rows_max+i);
for (int j = 0; j < beanAttrNames.size(); j++) {
String beanAttrName = (String)beanAttrNames.get(j);
String flag="";
if(flagListExists)
flag=(String)flagList.get(j);
for (int k = 0; k < props.length; k++) {
String propName = props[k].getName();
if (propName.equals(beanAttrName))
{
String pattern=dateMap.get(beanAttrName);
Cell cell = row.createCell((short)j);
Object cellValue = callGetter(bean, props[k],pattern);
if("true".equalsIgnoreCase(flag)){
if(result!=null){
HashMap hash=result.get(beanAttrName);
if(hash!=null)
cellValue=hash.get(cellValue);
}
}
if (cellValue == null) {
cellValue = "";
}
setExcelCellText2007(cell, cellValue.toString(),cellStyle);
}
}
}
//每当行数达到设置的值就刷新数据到硬盘,以清理内存
if(i%FLUSH_ROWS==0){
((SXSSFSheet)sheet).flushRows();
}
}
}
} catch (Exception e) {
throw new Exception(e);
}
}
/**
* 07、10办公版EXCEL导出,单元格设置
* @param cell 单元格对象
* @param text 单元格文本内容
* @param cellStyle 单元格格式
*/
private static void setExcelCellText2007(Cell cell, Object text,CellStyle cellStyle)
{
cell.setCellValue(text.toString());
cell.setCellType(1);//单元格类型
cell.setCellStyle(cellStyle);
}
/**
* 07、10办公版EXCEL导出,单元格宽度设置
* @param widthList 列宽集合
* @param sheet sheet对象
* @param allSize 总列数
*/
private static void setColumnWidth2007(List widthList,Sheet sheet,int allSize){
if(widthList!=null && widthList.size()>0){
int size=widthList.size();
for (int i = 0; i < size; i++) {
try {
Integer width=Integer.parseInt((String) widthList.get(i));
sheet.setColumnWidth((short) i,width*256);
} catch (NumberFormatException e) {
continue;
}
}
}else{
for (int i = 0; i < allSize; i++) {
try {
sheet.setColumnWidth((short) i,COLUMN_WIDTH_WORD*256);
} catch (NumberFormatException e) {
continue;
}
}
}
}
/**
* 03、WPS:EXCEL导出(数据直接写到服务器的EXCEL里,以下载的形式,下载导出的数据)
* @param listName 列表头名称
* @param beans 实体集合
* @param result 数字字典Map集
* @param filePath 服务器存放文件路径
* @param fileName 文件名称
* @param totalSize EXCEL条数量
* @param maxSheetSize sheet页条数量
* @return List 文件集合
* @throws Exception
*/
public static List beans2excelFile03(List listName,List beans,HashMap> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{
if(totalSize==null || totalSize<=0)
totalSize=TOTAL_SIZE;
if(maxSheetSize==null || maxSheetSize<=0)
maxSheetSize=MAX_SHEET_SIZE;
if(fileName==null)
fileName="";
return beans2excelFile2003(listName, beans, result, filePath, fileName,totalSize,maxSheetSize);
}
/**
* 03、WPS:EXCEL导出(数据直接写到服务器的EXCEL里,以下载的形式,下载导出的数据)
* @param listName 列表头名称
* @param beans 实体集合
* @param result 数字字典Map集
* @param filePath 服务器存放文件路径
* @param fileName 文件名称
* @param totalSize EXCEL条数量
* @param maxSheetSize sheet页条数量
* @param request 客户端请求对象
* @param response 客户端响应对象
* @throws Exception
*/
public static void beans2excelFile03(List listName,List beans,HashMap> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize,HttpServletRequest request,HttpServletResponse response) throws Exception{
if(totalSize==null || totalSize<=0)
totalSize=TOTAL_SIZE;
if(maxSheetSize==null || maxSheetSize<=0)
maxSheetSize=MAX_SHEET_SIZE;
if(fileName==null)
fileName="";
List files=beans2excelFile2003(listName, beans, result, filePath, fileName,totalSize,maxSheetSize);
DownLoadUtils.downLoadFiles(files, filePath, request, response);
}
/**
* 03、WPS:EXCEL导出,每个EXCEL组织数据
* @param listName 列表头名称
* @param beans 实体集合
* @param result 数字字典Map集
* @param filePath 服务器存放文件路径
* @param fileName 文件名称
* @param totalSize EXCEL条数量
* @param maxSheetSize sheet页条数量
* @return 文件集合
* @throws Exception
*/
private static List beans2excelFile2003(List listName,List beans,HashMap> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{
if ((listName == null) || (listName.size() == 0)) {
throw new Exception("listName is null when create excel document");
}
List listFile=new ArrayList();//返回的文件集合
int size=beans==null?0:beans.size();
String fileSuffixName=".xls";//后缀
String path="";//文件路径
Integer startIdx=0;//数据读取的起始行
Integer endIdx=0;//数据读取的结束行
(new File(filePath)).mkdirs(); //没有该目录创建目录
if(size==0){
startIdx=0;
endIdx=(totalSize)>size?size:(totalSize);
String name=fileName+"_第0-0条数据";
path=filePath+File.separatorChar+name+fileSuffixName;
HSSFWorkbook wb =new HSSFWorkbook();
buildExcelDocument2003(wb, listName, beans,result,startIdx,endIdx,maxSheetSize);
//没有文件,创建文件
File file = new File(path);
if (!file.exists()){
file.createNewFile();
}
FileOutputStream out=new FileOutputStream(file);
wb.write(out);
out.close();
return listFile;
}
for (int i = 0; i < size;i++) {
int remainder=i%totalSize;
if(size==0 || remainder==0){
startIdx=i;
endIdx=(i+totalSize)>size?size:(i+totalSize);
String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"条数据";
path=filePath+"/"+name+fileSuffixName;
HSSFWorkbook wb =new HSSFWorkbook();
buildExcelDocument2003(wb, listName, beans,result,startIdx,endIdx,maxSheetSize);
//没有文件,创建文件
File file = new File(path);
if (!file.exists()){
file.createNewFile();
}
FileOutputStream out=new FileOutputStream(file);
wb.write(out);
out.close();
listFile.add(file);
}else if((size-i)endIdx){//最后,不满一万条
startIdx=i;
endIdx=i+totalSize;
String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"条数据";
path=filePath+name+"."+fileSuffixName;//没有文件,创建文件
HSSFWorkbook wb =new HSSFWorkbook();
buildExcelDocument2003(wb, listName, beans, result,startIdx,endIdx,maxSheetSize);
//没有文件,创建文件
File file = new File(path);
if (!file.exists()){
file.createNewFile();
}
FileOutputStream out=new FileOutputStream(file);
wb.write(out);
out.close();
listFile.add(file);
}
}
return listFile;
}
/**
* 03,WPS:EXCEL导出,每个EXCEL写入数据
* @param wb EXCEL工作薄
* @param listName 列表头名称
* @param beans 实体集合
* @param result 数字字典Map集
* @param startIdx 数据集合,开始行
* @param endIdx 数据集合,结束始行
* @param maxSheetSize SHEET页条数
* @throws Exception
*/
private static void buildExcelDocument2003(HSSFWorkbook wb, List listName, List beans,HashMap> result,Integer startIdx,Integer endIdx,Integer maxSheetSize) throws Exception
{
int totalSize=endIdx-startIdx;//总共条数
try
{
CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);
List titles = new ArrayList();
List beanAttrNames = new ArrayList();
List widthList=new ArrayList();
String[] header = new String[listName.size()];
List flagList=new ArrayList();
boolean flagListExists=false;
int rows_max = 0;//标题占多少列
HashMap dateMap=new HashMap();
for (int i=0;i
{
String[] str=listName.get(i).split("&");
String en_name=str[0];
String zh_name=str[1];
beanAttrNames.add(i,en_name);
titles.add(i, zh_name);
header[i]=zh_name;
if (zh_name.split("_").length > rows_max) {
rows_max = zh_name.split("_").length;
}
if(str.length>2){
String flag=str[2];
flagList.add(i,flag);
if(!flagListExists)
flagListExists=true;
}
if(str.length>3){
widthList.add(str[3]);
}
if(str.length>4){
dateMap.put(en_name, str[4]);
}
}
PropertyDescriptor[] props = null;
int size=endIdx-startIdx;
HSSFSheet sheet=null;
//如果没有数据,导出表头
if(size==0){
sheet=ExcelHeadUtils.getExcelHead2003(wb, header, "Sheet1");
sheet.setDefaultRowHeight((short)350);//高度
setColumnWidth2003(widthList, sheet,beanAttrNames.size());
return ;
}
int u=1;//用来创建每个sheet的行
int h=0;//用来标注每个sheet也得名字:多少行-多少行
for (int i = startIdx; i < endIdx ; i++) {
int remainder=h%maxSheetSize;
if(size==0 || i==startIdx || remainder==0){
u=1;
int section=(h+maxSheetSize)>totalSize?totalSize:(h+maxSheetSize);
sheet=ExcelHeadUtils.getExcelHead2003(wb, header, "第"+(h+1)+"-"+section+"条");
sheet.createFreezePane( 1, rows_max, 1, rows_max);
sheet.setDefaultRowHeight((short)350);//高度
setColumnWidth2003(widthList, sheet,beanAttrNames.size());
}
if(props==null)
props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();
Object bean = beans.get(i);
HSSFRow row = sheet.createRow(u+rows_max-1);
u++;
h++;
for (int j = 0; j < beanAttrNames.size(); j++) {
String beanAttrName = (String)beanAttrNames.get(j);
String flag=null;
if(flagListExists)
flag=(String)flagList.get(j);
for (int k = 0; k < props.length; k++) {
String propName = props[k].getName();
if (propName.equals(beanAttrName))
{
String pattern=dateMap.get(beanAttrName);
HSSFCell cell = row.createCell((short)j);
Object cellValue = callGetter(bean, props[k],pattern);
if("true".equalsIgnoreCase(flag)){
if(result!=null){
HashMap hash=result.get(beanAttrName);
if(hash!=null)
cellValue=hash.get(cellValue);
}
}
if (cellValue == null) {
cellValue = "";
}
setExcelCellText2003(cell, cellValue.toString(),cellStyle);
}
}
}
}
} catch (Exception e) {
throw new Exception(e);
}
}
/**
* 03,WPS:EXCEL导出(直接以流的方式,写到客户端,导出的EXCEL文件只有一个)
* @param listName 列表头名称
* @param beans 实体集合
* @param maxSheetSize sheet页条数量
* @param outputStream 客户端输出流
* @throws Exception
*/
public static void beans2excelFile03(List listName,List beans,HashMap> result,String sheetName,Integer maxSheetSize, OutputStream outputStream) throws Exception{
if ((listName == null) || (listName.size() == 0)) {
throw new Exception("listName is null when create excel document");
}
if(maxSheetSize==null || maxSheetSize<=0){
maxSheetSize=MAX_SHEET_SIZE;
}
if(sheetName==null || "".equals(sheetName.trim())){
sheetName="Sheet";
}
HSSFWorkbook wb =new HSSFWorkbook();
if(maxSheetSize==null || maxSheetSize<=0)
maxSheetSize=MAX_SHEET_SIZE;
buildExcelDocument2003(wb, listName, beans,result,sheetName,maxSheetSize);
try {
wb.write(outputStream);
outputStream.close();
} catch (IOException e) {
throw new Exception(e);
}
}
/**
* 03,WPS:EXCEL导出,EXCEL写入数据
* @param wb EXCEL工作薄
* @param listName 列表头名称
* @param beans 实体集合
* @param maxSheetSize sheet页条数量
* @throws Exception
*/
private static void buildExcelDocument2003(HSSFWorkbook wb, List listName, List beans,HashMap> result,String sheetName,Integer maxSheetSize) throws Exception
{
try
{
CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);
List titles = new ArrayList();
List beanAttrNames = new ArrayList();
List widthList = new ArrayList();
HashMap dateMap=new HashMap();
String[] header = new String[listName.size()];
int rows_max = 0;//标题占多少列
List flagList=new ArrayList();
boolean flagListExists=false;
for (int i=0;i
{
String[] str=listName.get(i).split("&");
String en_name=str[0];
String zh_name=str[1];
beanAttrNames.add(i,en_name);
titles.add(i, zh_name);
header[i]=zh_name;
if (zh_name.split("_").length > rows_max) {
rows_max = zh_name.split("_").length;
}
if(str.length>2){
String flag=str[2];
flagList.add(i,flag);
if(!flagListExists)
flagListExists=true;
}
if(str.length>3){
widthList.add(str[3]);
}
if(str.length>4){
dateMap.put(en_name, str[4]);
}
}
PropertyDescriptor[] props =null;
int size=beans==null?0:beans.size();
HSSFSheet sheet=null;
//如果没有数据,导出表头
if(size==0){
sheet=ExcelHeadUtils.getExcelHead2003(wb, header, sheetName);
setColumnWidth2003(widthList, sheet,beanAttrNames.size());
sheet.setDefaultRowHeight((short)350);//高度
return ;
}
for (int i = 0; i < size ; i++) {
int remainder=i%maxSheetSize;
if(size==0 || i==0 || remainder==0){
sheet=ExcelHeadUtils.getExcelHead2003(wb, header, sheetName+(i/maxSheetSize));
sheet.createFreezePane( 1, rows_max, 1, rows_max);
setColumnWidth2003(widthList, sheet,beanAttrNames.size());
sheet.setDefaultRowHeight((short)350);//高度
}
if(props==null)
props= Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();
Object bean = beans.get(i);
HSSFRow row = sheet.createRow(remainder+rows_max);
for (int j = 0; j < beanAttrNames.size(); j++) {
String beanAttrName = (String)beanAttrNames.get(j);
String flag=null;
if(flagListExists)
flag=(String)flagList.get(j);
for (int k = 0; k < props.length; k++) {
String propName = props[k].getName();
if (propName.equals(beanAttrName))
{
String pattern=dateMap.get(beanAttrName);
HSSFCell cell = row.createCell((short)j);
Object cellValue = callGetter(bean, props[k],pattern);
if("true".equalsIgnoreCase(flag)){
if(result!=null){
HashMap hash=result.get(beanAttrName);
if(hash!=null)
cellValue=hash.get(cellValue);
}
}
if (cellValue == null) {
cellValue = "";
}
setExcelCellText2003(cell, cellValue.toString(),cellStyle);
}
}
}
}
} catch (Exception e) {
throw new Exception(e);
}
}
/**
* 03,WPS:EXCEL导出,单元格设置
* @param cell 单元格对象
* @param text 单元格文本内容
* @param cellStyle 单元格格式
*/
private static void setExcelCellText2003(HSSFCell cell, Object text,CellStyle cellStyle)
{
cell.setCellValue(text.toString());
cell.setCellType(1);//单元格类型
cell.setCellStyle(cellStyle);
}
/**
* 03,WPS:EXCEL导出,单元格宽度设置
* @param widthList 列宽集合
* @param sheet sheet对象
* @param allSize 总列数
*/
private static void setColumnWidth2003(List widthList,HSSFSheet sheet,int allSize){
if(widthList!=null && widthList.size()>0){
int size=widthList.size();
for (int i = 0; i < size; i++) {
try {
Integer width=Integer.parseInt((String) widthList.get(i));
sheet.setColumnWidth((short) i,width*256);
} catch (NumberFormatException e) {
continue;
}
}
}else{
for (int i = 0; i < allSize; i++) {
try {
sheet.setColumnWidth((short) i,COLUMN_WIDTH_WORD*256);
} catch (NumberFormatException e) {
continue;
}
}
}
}
/**
* 根据反射,获取实体属性的值
* @param target 实体属性
* @param prop 反射调用类
* @param pattern 日期格式
* @return
*/
private static Object callGetter(Object target, PropertyDescriptor prop,String pattern) {
Object o = null;
if (prop.getReadMethod() != null) {
try {
o = prop.getReadMethod().invoke(target, null);
if (Date.class.equals(prop.getPropertyType())) {
if(pattern!=null && !"".equals(pattern)){
try {
o = new SimpleDateFormat(pattern).format(o);
} catch (Exception e) {
o = new SimpleDateFormat(PATTERN).format(o);
}
}else{
o = formatDate(o);
}
}
} catch (Exception e) {
o = null;
}
}
return o;
}
/**
* 日期转换
* @param date
* @return 字符串的日期
*/
private static String formatDate(Object date) {
if(date==null)
return "";
String dateStr = new SimpleDateFormat(DATE_HH_PATTERN).format(date);
if("00:00:00".equals(dateStr)){
return new SimpleDateFormat(DATE_PATTERN).format(date);
}
return new SimpleDateFormat(PATTERN).format(date);
}
}
然后看看效果吧:
[转载]Java导出Excel
一.需求介绍 当前B/S模式已成为应用开发的主流,而在开发企业办公系统的过程中,常常有客户这样子要求:把系统数据库中的数据导出到Excel,用户查看报表时直接用Excel打开.或者是:用户已经习惯用E ...
java导出excel报错:getOutputStream() has already been called for this response
对于java导出excel报错的问题,查了很多都说是在使用完输出流以后调用以下两行代码即可 out.clear(); out = pageContext.pushBody(); 但这也许是页面上输出时 ...
java导出excel报表
1.java导出excel报表: package cn.jcenterhome.util; import java.io.OutputStream;import java.util.List;impo ...
Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类
Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...
java导出excel表格
java导出excel表格: 1.导入jar包 org.apache.poi
Java导出Excel和CSV(简单Demo)
Java导出Excel和CSV的简单实现,分别使用POI和JavaCSV. JavaBean public class ReportInfo { int id; String date; int nu ...
java导出excel模板数据
Java导出excel数据模板,这里直接贴代码开发,流程性的走下去就是步骤: String[] colName=new String[]{"期间","科目代码" ...
java导出excel工具类
java导出excel须要使用HSSFWorkbook这个类,须要导入poi-3.6-20091214.jar 工具类调用例如以下: package com.qlwb.business.util; i ...
JAVA 导出 Excel, 将Excel下载到本地
昨天说了如何将数据导出成 excel 的两种方式,今天完善一下将 java 导出(文件在服务器)并下载到本地 1. 触发导出 ajax 代码 $.ajax({ type: "POST&quo ...
随机推荐
PHP文件大小格式化函数合集
比如碰到一个很大的文件有49957289167B,大家一看这么一长串的数字后面单位是字节B,还是不知道这个文件的大小是一个什么概念,我们把它转换成GB为单位,就是46.53GB.用下面这些函数就可以完 ...
通用PE工具箱 4.0精简优化版
通用PE工具箱 4.0精简优化版 经用过不少 WinPE 系统,都不是很满意,普遍存在篡改主页.添加广告链接至收藏夹.未经允许安装推广软件等流氓行为,还集成了诸多不常用的工具,令人头疼不已.那么今天给 ...
C#中timer类的用法
C#中timer类的用法 关于C#中timer类 在C#里关于定时器类就有3个 1.定义在System.Windows.Forms里 2.定义在System.Threading.Timer类 ...
如何用linux命令查看nginx是否在正常运行
有时想知道nigix是否在正常运行,需要用linux命令查看nginx运行情况. 执行命令: ps -A | grep nginx 如果返回结果的话,说明有nginx在运行,服务已经启动. 如果 ...
JavaScript----遇到的问题
存在 ...
vector内存分配
vector,map 这些容器还是在堆上分配的内存,在析构时是释放空间 vector在提高性能可以先reserve在push_back() reserve:决定capacity,但没有真正的分配内存, ...
Listview加载更多是,恢复到原来的位置,如果不加特殊处理,总是跳转第一条
1.记录listView滚动到的位置的坐标,然后利用listView.scrollTo精确的进行恢复 listView.setOnScrollListener(new OnScrollListener ...
自然语言.例如:求n!。
(1).定义3个变量i.n及mul,并为i和mul均赋初值为1. (2).从键盘中输入一个数赋给n. (3).将mul乘以i的结果赋给mul. (4)i的值加1,判断i的值是否大于n.如果大于n,则执 ...
[APIO2010]
A.特别行动队 n<=1000000 看了数据范围和题目感觉就像是斜率优化,然后瞎推了一波式子,没想到A了. sij表示i+1到j的权值和. j比k优秀 $$fj+a*sij^{2}+b*si ...
md5 加密文件
import hashlibimport os def get_md5(file_path): md5 = None if os.path.isfile(file_path): f = open(fi ...
java excel导出下载_Java导出excel并下载功能相关推荐
- java中excel上传_java对excel表格的上传和下载处理
Excel表格文件的上传和下载,java中涉及到文件肯定会有io流的知识. 而excel文件就要涉及到poi技术,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为 ...
- java html 转图片_Java 将Excel转为图片、html、XPS、XML、CSV
通过文档格式转换,可满足不同办公场合对文档操作的需求.本文将介绍转换Excel文档为其他常见文档格式的方法.通过文中的方法,可支持将Excel转换为包括PDF.图片.html.XPS.XML.CSV. ...
- java 表格 列删除_Java 删除Excel表格中的空白行或列
Java 删除Excel表格中的空白行和列 本文介绍在Java程序中如何来删除Excel表格中多余的空白行或者列. 使用工具:Free Spire.XLS for Java (免费版) Jar获取及导 ...
- java excel行高_Java 设置Excel自适应行高、列宽
在excel中,可通过设置自适应行高或列宽自动排版,是一种比较常用的快速调整表格整体布局的方法.设置自适应时,可考虑2种情况: 1.固定数据,设置行高.列宽自适应数据(常见的设置自适应方法) 2.固定 ...
- java excel 展开折叠_Java 刷新Excel透视表,折叠/展开Excel透视表中的行
概述 透视表是依据已有数据源来创建的交互式表格,我们可在excel中创建透视表,也可编辑已有透视表. 所需工具:Free Spire.XLS for Java免费版,编辑代码前,先下载导入jar到Ja ...
- java编译器下载_java手机版编译器下载
java编译器安卓版是一款专为java开发人员服务的编辑客户端应用,利用java编译器手机安卓版实时进行相关编辑还能进行简单的编译,运行单个小程序等,提供您的效率. 功能介绍 java编译器安卓版是一 ...
- java me下载_Java ME SDK下载_Java ME SDK官方下载-太平洋下载中心
新的Java ME SDK已经正式发布了.Java ME曾是Sun的一个巨大成功,不过近些年来Java ME技术一直徘徊不前.今年七月份,在经历一番人事调整后Java ME SDK团队正式宣布回归,并 ...
- java ftp 设置编码_java ftp上传下载,下载文件编码设置
/** * Description: 从FTP服务器下载文件 * @Version1.0 Jul 27, 2008 5:32:36 PM by 崔红保(cuihongbao@d-heaven.com) ...
- java生成excel文件步骤_java导出Excel文件的步骤全纪录
一.背景 当前b/s模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用excel打开(电信系统.银行系统).或者是:我们已经习惯用excel打印.这样在我们实际 ...
- java导出类_java导出excel工具类
java导出excel须要使用HSSFWorkbook这个类,须要导入poi-3.6-20091214.jar 工具类调用例如以下: package com.qlwb.business.util; i ...
最新文章
- NOIP2013普及组 T2 表达式求值
- 高级持续性威胁检测无法检测出自定义恶意软件?
- 什么是AI“智慧芯片”?清华魏少军提出11点基本要素
- 用 Go 构建一个区块链 -- Part 5: 地址 1
- 线程故事:Web应用程序中的ThreadLocal
- 软工专硕考研_2021考研人数将突破400万?录取率或成史低!
- iSCSI远程块存储配置实验
- red5 + java+flex free download_Flex 4 +Red5 流媒体使用研究2——Flex4的VideoPlayer控件应用...
- office2007过期后没有输入序列号对话框的激活方法
- 智能家居系统--KNX现场实施图片01
- 2020vue面试题汇总
- Apollo 算法阅读之Public Road轨迹规划算法--路径规划(含源代码)
- SM2算法+开发中注意事项
- android红外线开发实例,Android实例-红外线操作(XE10.2+小米5)
- 电子钱包CPU卡和PSAM卡消费密钥装载分析
- 剑指offer-丑数(Java)
- MySQL 8.0踩到的坑(2)
- 机器学习实战 | Python 信用卡欺诈检测其实特简单
- UNIZEN每周洞察第四期:Unizen生态迎来丰富进展
- 微信支付--采坑记(1)