实现导出Excel功能!

狗阳 2011-10-19 07:34:21
展示报表页面可以预览,预览时提供导出Excel,把报表页面显示的结果以Excel的形式导出。
有例子贴个例子,谢谢!不要发连接。公司上不了外网。
...全文
302 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
zouyang2005 2011-10-20
  • 打赏
  • 举报
回复
poi工具包实现生成文件,然后提供下载功能,网上代码很多的
zhu6100441 2011-10-20
  • 打赏
  • 举报
回复
又碰一CSDN的内部工作人员,话说,你们WEB服务器也在你们的内部局域网中么?
  • 打赏
  • 举报
回复
上百度搜 ”poi“这个东东,就有了。。。代码多的是,记得要导入poi的那几个jar包,网上也有。。
luyun2011 2011-10-20
  • 打赏
  • 举报
回复
用jxl和poi jar包都可以导出Excel
下面是jxl包的用法:

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Random;

import com.neusoft.tqms.vo.OrganVO;
import com.neusoft.tqms.vo.ParameterVO;
import com.neusoft.tqms.vo.TraineesVO;
import com.neusoft.tqms.vo.TrainingProjectVO;
import com.neusoft.tqms.vo.UserVO;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import jxl.format.Alignment;
import jxl.format.Colour;

public class Excel {
/**
* 存放文件目录名
*/
public String fullDir="";
//定义File对象
private File f=null;
/**
* 定义导出的文件名
*/
public String fileName="";
//定义WritableWorkbook对象
private WritableWorkbook book=null;
//定义工作表
private WritableSheet sheet=null;
//标题单元格样式
private WritableCellFormat cellTitle=null;
//头部单元格样式
private WritableCellFormat cellHead=null;
//结果集单元格样式
private WritableCellFormat cellResult=null;
//格式字体
private WritableFont wft=null;
private WritableFont wfh=null;
/**
* 构造函数,初始化Excel
*/
public Excel(){
try {
//文件保存目录
String url=Excel.class.getResource("/").toString();
//url:file:/C:/tomcat5.5/webapps/tqms/WEB-INF/classes/
int lastIndex=url.length()-16;
//去掉路径中的"file:/"和"WEB-INF/classes/"
String filePath=url.toString().substring(6,lastIndex)+"export/";
f=new File(filePath);
//在filePath下创建文件夹
f.mkdirs();
//定义日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmm");
String nameFirst=sdf.format(new java.util.Date());
Random ra = new Random();
String nameLast = String.valueOf(ra.nextInt(999));
//保存的EXCEL文件名
fileName=nameFirst+nameLast;
//EXCEL存放目录(绝对路径)
fullDir = filePath+fileName+".xls";
//创建目录
f.mkdirs();
//创建WritableWorkbook对象
book=Workbook.createWorkbook(new File(fullDir));
//sheet工作表名称
sheet = book.createSheet("导出数据信息", 0);
//初始化标题单元格
cellTitle = new WritableCellFormat();
//初始化头部单元格
cellHead = new WritableCellFormat();
//初始化结果集单元格
cellResult = new WritableCellFormat();
//定义字体样式
wft = new WritableFont(WritableFont.createFont("宋体"),18,WritableFont.BOLD);
//设置颜色
wft.setColour(Colour.BLUE);
wfh = new WritableFont(WritableFont.createFont("宋体"),14,WritableFont.BOLD);
//为标题和表头分配样式
cellTitle.setFont(wft);
//对齐方式
cellTitle.setAlignment(Alignment.CENTRE);
//头部字体格式
cellHead.setFont(wfh);
//头部对齐格式
cellHead.setAlignment(Alignment.CENTRE);
//正文格式
cellResult.setAlignment(Alignment.CENTRE);
cellResult.setWrap(true);
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
/**
*
* Create date:Apr 4, 2011
* Method name:exportUserData
* Description: [导出数据]
* return:void
*/
public void exportUserData(List<UserVO> userList){
int count = userList.size();
try {
//(开始列,开始行,结束列,结束行),合并第一行的第1-8列
sheet.mergeCells(0, 0, 7, 0);
//设置每一列宽度均为20
for(int i=0;i<8;i++){
sheet.setColumnView(i, 20);
}
//标题列
Label la1 = new Label(0,0,"用户信息");
la1.setCellFormat(cellTitle);
Label[] lhead = new Label[8];
//结果集为count行,7列(字段数)
Label[][] lresult = new Label[count][8];
//(列数,行数,单元格内容)
lhead[0] = new Label(0,1,"人员编码");
lhead[1] = new Label(1,1,"机构");
lhead[2] = new Label(2,1,"部门");
lhead[3] = new Label(3,1,"职务");
lhead[4] = new Label(4,1,"姓名");
lhead[5] = new Label(5,1,"性别");
lhead[6] = new Label(6,1,"电话");
lhead[7] = new Label(7,1,"E-MAIL");
for(int i=0;i<count;i++){
UserVO user=userList.get(i);
//(列数,行数,单元格内容)
lresult[i][0] = new Label(0,i+2,user.getUserCode());
//给第二列(机构)赋值
lresult[i][1] = new Label(1,i+2,user.getOrgan());
//给第三列(部门)赋值
lresult[i][2] = new Label(2,i+2,user.getDepartment());
//给第四列(职务)赋值
lresult[i][3] = new Label(3,i+2,user.getPosition());
//给第五列(姓名)赋值
lresult[i][4] = new Label(4,i+2,user.getUserName());
//给第六列(性别)赋值
lresult[i][5] = new Label(5,i+2,user.getUserSex());
//给第七列(电话)赋值
lresult[i][6] = new Label(6,i+2,user.getTelephone());
//给第八列(E-MAIL)赋值
lresult[i][7] = new Label(7,i+2,user.getEmail());
//将字段加入工作表
for(int j=0;j<8;j++){
//结果集单元格格式
lresult[i][j].setCellFormat(cellResult);
//添加到sheet中
sheet.addCell(lresult[i][j]);
}
}
//将头部标题舔到工作表
sheet.addCell(la1);
for(int k=0;k<8;k++){
//设置标题栏样式
lhead[k].setCellFormat(cellHead);
//将标题舔到工作表
sheet.addCell(lhead[k]);
}
//写入数据
book.write();
//关闭文件
book.close();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
kouyiSC 2011-10-20
  • 打赏
  • 举报
回复
预览应该是他报表的功能。。。这个功能是他的程序应该具备的,写一个查询不就可以了。
下载的时候也支持预览。。。。。。
py1025677845 2011-10-20
  • 打赏
  • 举报
回复
下载的时候不是有个打开和保存吗
直接打开不就是预览了么。
剑神一笑 2011-10-20
  • 打赏
  • 举报
回复
别人要预览的功能
只是下载很容易的
上面粗略看一下都可以
kouyiSC 2011-10-20
  • 打赏
  • 举报
回复
基本步骤:点击导出-》后台生成excel放在demp临时文件夹--》下载excel

public class Excel {

/**
*
* 生成EXCEL文件并导出数据
*
* @param path
* 文件路径
* @param sheetNums
* 创建工作表数量
* @param sheetNames
* 多个工作表对应的名称
* @param titles
* 表头数组
* @param 写入excel中的正文数据
* 表头数组
* @return file
* 返回生成的xls文件
* @throws Exception
*/
public File CreateExcel(String path, int sheetNums, String[] sheetNames, String[] titles, Object[] objects, HttpServletResponse response) throws Exception
{
if(Utils.isNull(path)){
throw new Exception("请指定导出文件的路径!");}
if(Utils.isNull_1(sheetNums)){
throw new Exception("请指定EXCEL工作表数量!");}
if(Utils.isNull(sheetNames)){
throw new Exception("请指定EXCEL工作表名称!");}
if(sheetNums != sheetNames.length){
throw new Exception("工作表数量参数必须与名称参数长度一致!");}
if(Utils.isNull(titles)){
throw new Exception("请为Excel文件指定表头!");}
if(Utils.isNull(objects)){
throw new Exception("请为Excel文件设置正文!");}

// 当前时间字符串组成excel文件名称
String xlsName = path + "tokenlog_" + DateNowStr() + ".xls";
File file = new File(xlsName);

OutputStream ot = new FileOutputStream(file);
// 创建excel文件
WritableWorkbook wwb = Workbook.createWorkbook(ot);

// 设置表头字体
WritableFont wtitlefont = new WritableFont(WritableFont.TIMES, 11, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat titleformat = new WritableCellFormat(wtitlefont);

// 创建工作表
for(int num = 0; num < sheetNums; num++)
{
WritableSheet sheet = wwb.createSheet(sheetNames[num], 0);
// 设置excel表头
int row =0;
int column = 0;
for(String title : titles){
Label label0 = new Label(column, row, title, titleformat);
sheet.addCell(label0);
column ++;
}
// 写入正文
SetSheetCell(sheet, objects[num]);
}

// 提交写入数据并关闭
wwb.write();
wwb.close();
ot.close();
return file;
}

/**
* 写入正文--可配置
* @param sheet
* @param objects
* @throws RowsExceededException
* @throws WriteException
*/
private void SetSheetCell(WritableSheet sheet, Object objects) throws RowsExceededException, WriteException
{
// 设置正文字体
WritableFont wcellfont = new WritableFont(WritableFont.TIMES, 11, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat cellformat = new WritableCellFormat(wcellfont);
int number = 1001;
HashMap<Integer, String> map = GetXMLConfigProperty.ExcelHeader();
int id = 1; // 记录编号
int row = 1;
int column = 0;
RadiusAuditInfo[] audits = (RadiusAuditInfo[])objects;
for(RadiusAuditInfo audit : audits)
{
if(map.get(number).equals("true")){
Label label1 = new Label(column, row, String.valueOf(id), cellformat);
sheet.addCell(label1);
column ++;
}
number ++;
if(map.get(number).equals("true")){
Label label2 = new Label(column, row, audit.getResourceid(), cellformat);
sheet.addCell(label2);
column ++;
}
number ++;
if(map.get(number).equals("true")){
Label label3 = new Label(column, row, audit.getResourcename(), cellformat);
sheet.addCell(label3);
column ++;
}
number ++;
if(map.get(number).equals("true")){
Integer type = Integer.parseInt(audit.getLocalname());
String[] localtype = GetXMLConfigProperty.getLocaltype();
String localname = "系统主机";
for (int j = 0; j < localtype.length; j++) {
if (type == j)
localname = localtype[type];
}
Label label4 = new Label(column, row, localname, cellformat);
sheet.addCell(label4);
column ++;
}
number ++;
if(map.get(number).equals("true")){
Label label5 = new Label(column, row, audit.getAddress(), cellformat);
sheet.addCell(label5);
column ++;
}
number ++;
if(map.get(number).equals("true")){
Label label6 = new Label(column, row, audit.getAuthuserid(), cellformat);
sheet.addCell(label6);
column ++;
}
number ++;
if(map.get(number).equals("true")){
Label label7 = new Label(column, row, audit.getId_user(), cellformat);
sheet.addCell(label7);
column ++;
}
number ++;
if(map.get(number).equals("true")){
Label label8 = new Label(column, row, audit.getIsbypass() == 0 ? "否" : "是", cellformat);
sheet.addCell(label8);
column ++;
}
number ++;
if(map.get(number).equals("true")){
Label label9 = new Label(column, row, audit.getEquipno() != null ? audit.getEquipno() : "静态口令", cellformat);
sheet.addCell(label9);
column ++;
}
number ++;
if(map.get(number).equals("true")){
Label label10 = new Label(column, row, audit.getAuthresultcode(), cellformat);
sheet.addCell(label10);
column ++;
}
number ++;
if(map.get(number).equals("true")){
Label label11 = new Label(column, row, audit.getAuthresultcode().equals("00000") ? "认证成功" : "认证失败", cellformat);
sheet.addCell(label11);
column ++;
}
number ++;
if(map.get(number).equals("true")){
Label label12 = new Label(column, row, audit.getRemark(), cellformat);
sheet.addCell(label12);
column ++;
}
row ++;
id ++ ;
column = 0;
number = 1001;
}
}

/**
* 获取当前时间组成的字符串,用来组成excel命令
* @return
*/
public static String DateNowStr(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = new Date();
String dateStr = format.format(date);
String excelName = ((dateStr.replaceAll("-", "")).replaceAll(":", "")).replaceAll("\\s+", "");
return excelName;
}


/**
* 下载文件
* @param filePath
* @param filename
* @param response
* @throws Exception
*/
public static void download(String filePath, String filename, HttpServletResponse response) throws Exception{
// TODO Auto-generated method stub
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;

File uploadFile = new File(filePath);
fis = new FileInputStream(uploadFile);
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
//filePath = URLEncoder.encode(filePath, "UTF-8");

//弹出下载对话框的关键代码
response.setContentType("application/x-download");
response.setHeader("Content-Disposition","attachment;filename="+filename);
int bytesRead = 0;
//都是用输入流进行先读,然后用输出流去写,用的是缓冲输入输出流
byte[] buffer = new byte[8192];
while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
try{
bos.write(buffer, 0, bytesRead);
}catch(Exception e){}
}
try{bos.flush();}catch(Exception e){}
try{fis.close();}catch(Exception e){}
try{bis.close();}catch(Exception e){}
try{fos.close();}catch(Exception e){}
try{bos.close();}catch(Exception e){}
}
Cactus_hxk 2011-10-19
  • 打赏
  • 举报
回复
这是我写的一个到出客户的例子,该方法是我接口的实现类中的方法,需要一个jar包:poi-3.0.2.jar

public boolean exportExcel(ExportCustomerDto expDto)
throws Exception
{
boolean isSuccess = false;
//开始构造导出Excel文件名称
StringBuffer fileNameBuffer = new StringBuffer();
fileNameBuffer.append(CustomerConstants.EXPORT_CUS_FILENAME);
SimpleDateFormat fmtDate = new SimpleDateFormat("yyyyMMddHHmmss");
fileNameBuffer.append(fmtDate.format(new Date()));
fileNameBuffer.append((int) (10F * (new Random()).nextFloat()));
fileNameBuffer.append(".xls");
//构造导出Excel文件名称完成

HSSFWorkbook workbook = new HSSFWorkbook(); // 产生工作簿对象
HSSFSheet sheet = workbook.createSheet(); // 产生工作表对象
// 设置第一个工作表的名称为firstSheet
// 为了工作表能支持中文,设置字符编码为UTF_16
workbook.setSheetName(0, "客户批量导出", HSSFWorkbook.ENCODING_UTF_16);
// 产生一行
HSSFRow row = sheet.createRow((short) 0);
// 产生第一个单元格
String[] tableHead = {"姓名","电话","性别"................};
for (int i = 0; i < tableHead.length; i++)
{
HSSFCell cell = row.createCell((short) i);
// 设置单元格内容为字符串型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
// 为了能在单元格中写入中文,设置字符编码为UTF_16。
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
// 往第一个单元格中写入信息
cell.setCellValue(tableHead[i]);
}

List list = cusExportDao.cusExportList(expDto);//从数据库查的所有客户List
int rowcount = 0;

for (int j = 0; j < list.size(); j++)
{
ExportCustomerDto dto = (ExportCustomerDto) list.get(j);
rowcount = j + 1;
// 产生一行
HSSFRow row2 = sheet.createRow((short) rowcount);

for (int k = 0; k < tableHead.length; k++)
{
HSSFCell cell2 = row2.createCell((short) k);
// 设置单元格内容为字符串型
cell2.setCellType(HSSFCell.CELL_TYPE_STRING);
// 为了能在单元格中写入中文,设置字符编码为UTF_16。
cell2.setEncoding(HSSFCell.ENCODING_UTF_16);
// 往第一个单元格中写入信息

if (k == 0)
{
cell2.setCellValue(dto.getCustomerName());
}
if (k == 1)
{
cell2.setCellValue(dto.getStrCustomerType());
}
if (k == 2)
{
cell2.setCellValue(dto.getStrSex());
}
if (k == 3)
{
cell2.setCellValue(dto.getPersonCardId());
}
if (k == 4)
{
cell2.setCellValue(dto.getTelPhone());
}
if (k == 5)
{
cell2.setCellValue(dto.getCellPhone());
}
if (k == 6)
{
cell2.setCellValue(dto.getAddress());
}
if (k == 7)
{
cell2.setCellValue(dto.getMailCode());
}
if (k == 8)
{
cell2.setCellValue(dto.getEmail());
}
if (k == 9)
{
cell2.setCellValue(dto.getViteDate());
}
if (k == 10)
{
cell2.setCellValue(dto.getSaleGuid());
}

// ////这里要加入要写到EXCEL表格中去的值
}
}
String fullFileName = System.getProperty("java.io.tmpdir") + "\\" + fileNameBuffer.toString();
expDto.setFilepath(fullFileName);
System.out.println(expDto.getFilepath());

FileOutputStream fOut = new FileOutputStream(fullFileName);
workbook.write(fOut);
fOut.flush();
fOut.close();
isSuccess = true;
return isSuccess;
}
CCTTVVBB 2011-10-19
  • 打赏
  • 举报
回复
response.setHeader()
瑞恩_张 2011-10-19
  • 打赏
  • 举报
回复
额、难道csdn不算外网 - -#
具体内容请参考我的BLOG:http://blog.csdn.net/smallwhiteyt/archive/2009/11/08/4784771.aspx 如果你耐心仔细看完本文,相信以后再遇到导出EXCLE操作的时候你会很顺手觉得SO EASY,主要给新手朋友们看的,老鸟可以直接飘过了,花了一晚上的时间写的很辛苦,如果觉得对你有帮助烦请留言支持一下,我会写更多基础的原创内容来回报大家。 C#导出数据到EXCEL表格是个老生常谈的问题了,写这篇文章主要是给和我一样的新手朋友提供两种导出EXCEL的方法并探讨一下导出的效率问题,本文中的代码直接就可用,其中部分代码参考其他的代码并做了修改,抛砖引玉,希望大家一起探讨,如有不对的地方还请大家多多包涵并指出来,我也是个新手,出错也是难免的。 首先先总结下自己知道的导出EXCEL表格的方法,大致有以下几种,有疏漏的请大家补充。 1.数据逐条逐条的写入EXCEL 2.通过OLEDB把EXCEL做为数据源来写 3.通过RANGE范围写入多行多列内存数据到EXCEL 4.利用系统剪贴板写入EXCEL 好了,我想这些方法已经足够完成我们要实现功能了,方法不在多,在精,不是么?以上4中方法都可以实现导出EXCEL,方法1为最基础的方法,意思就是效率可能不是太高,当遇到数据量过大时所要付出的时间也是巨大的,后面3种方法都是第一种的衍生,在第一种方法效率低下的基础上改进的,这里主要就是一个效率问题了,当然如果你数据量都很小,我想4种方法就代码量和复杂程度来说第1种基本方法就可以了,或当你的硬件非常牛逼了,那再差的方法也可以高效的完成也没有探讨的实际意义了,呵呵说远了,本文主要是在不考虑硬件或同等硬件条件下单从软件角度出发探讨较好的解决方案。

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧