导出Excel表格
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileOutputStream;
import java.io.FileInputStream;
public class CreateXL
{
public static String xlsFile="test.xls"; //产生的Excel文件的名称
public static void main(String args[])
{
try
{
HSSFWorkbook workbook = new HSSFWorkbook(); //产生工作簿对象
HSSFSheet sheet = workbook.createSheet(); //产生工作表对象
//设置第一个工作表的名称为firstSheet
//为了工作表能支持中文,设置字符编码为UTF_16
workbook.setSheetName(0,"firstSheet",HSSFWorkbook.ENCODING_UTF_16);
//产生一行
HSSFRow row = sheet.createRow((short)0);
//产生第一个单元格
HSSFCell cell = row.createCell((short) 0);
//设置单元格内容为字符串型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
//为了能在单元格中写入中文,设置字符编码为UTF_16。
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
//往第一个单元格中写入信息
cell.setCellValue("测试成功");
FileOutputStream fOut = new FileOutputStream(xlsFile);
workbook.write(fOut);
fOut.flush();
fOut.close();
System.out.println("文件生成...");
//以下语句读取生成的Excel文件内容
FileInputStream fIn=new FileInputStream(xlsFile);
HSSFWorkbook readWorkBook= new HSSFWorkbook(fIn);
HSSFSheet readSheet= readWorkBook.getSheet("firstSheet");
HSSFRow readRow =readSheet.getRow(0);
HSSFCell readCell = readRow.getCell((short)0);
System.out.println("第一个单元是:" + readCell.getStringCellValue());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
与数据库结合使用
使用POI,结合JDBC编程技术,我们就可以方便地将数据库中的数据导出生成Excel报表。其关键代码如下:
/*把数据集rs中的数据导出至Excel工作表中。
*传入参数:数据集rs,Excel文件名称xlsName,工作表名称sheetName。
*/
public static void resultSetToExcel(ResultSet rs,String xlsName,String sheetName) throws Exception
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
workbook.setSheetName(0,sheetName,HSSFWorkbook.ENCODING_UTF_16);
HSSFRow row= sheet.createRow((short)0);;
HSSFCell cell;
ResultSetMetaData md=rs.getMetaData();
int nColumn=md.getColumnCount();
//写入各个字段的名称
for(int i=1;i<=nColumn;i++)
{
cell = row.createCell((short)(i-1));
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(md.getColumnLabel(i));
}
int iRow=1;
//写入各条记录,每条记录对应Excel中的一行
while(rs.next())
{row= sheet.createRow((short)iRow);;
for(int j=1;j<=nColumn;j++)
{
cell = row.createCell((short)(j-1));
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(rs.getObject(j).toString());
}
iRow++;
}
FileOutputStream fOut = new FileOutputStream(xlsName);
workbook.write(fOut);
fOut.flush();
fOut.close();
JOptionPane.showMessageDialog(null,"导出数据成功!");
}
POI功能强大,还可以设置单元格格式、设置页眉页脚等.
导出Excel表格
package zjx;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import dao.ProductDao;
import dao.impl.ProductDaoImpl;
import entity.Product;
import jxl.*;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.CellFormat;
import jxl.write.Boolean;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class DemoXls {
/**
* 数据库导出至Excel表格
*/
public static void main(String[] args) {
// 准备设置excel工作表的标题
String[] title = {"编号","产品名称","产品类型","计量类型"};
try {
// 获得开始时间
long start = System.currentTimeMillis();
// 输出的excel的路径
String filePath = "e:\\testJXL2.xls";
// 创建Excel工作薄
WritableWorkbook wwb;
// 新建立一个jxl文件,即在e盘下生成testJXL.xls
OutputStream os = new FileOutputStream(filePath);
wwb=Workbook.createWorkbook(os);
// 添加第一个工作表并设置第一个Sheet的名字
WritableSheet sheet = wwb.createSheet("产品清单", 0);
Label label;
for(int i=0;i<title.length;i++){
// Label(x,y,z) 代表单元格的第x+1列,第y+1行, 内容z
// 在Label对象的子对象中指明单元格的位置和内容
label = new Label(i,0,title[i]);
// 将定义好的单元格添加到工作表中
sheet.addCell(label);
}
// 下面是填充数据
/*
* 保存数字到单元格,需要使用jxl.write.Number
* 必须使用其完整路径,否则会出现错误
* */
ProductDao dao=new ProductDaoImpl();
List<Product> list=dao.queryAll();
for(int i=0;i<list.size();i++){
sheet.setRowView(i,400);
// 填充产品编号
jxl.write.Number number = new jxl.write.Number(0,i+1,list.get(i).getProductId());
sheet.addCell(number);
// 填充产品名称
label = new Label(1,i+1,list.get(i).getProductName());
sheet.addCell(label);
jxl.write.Number type = new jxl.write.Number(2,i+1,list.get(i).getProductTypeId());
sheet.addCell(type);
jxl.write.Number measure = new jxl.write.Number(3,i+1,list.get(i).getMeasureTypeId());
sheet.addCell(measure);
Label label2 = new Label(1,i+1,list.get(i).getSource());
sheet.addCell(label2);
}
// 写入数据
wwb.write();
// 关闭文件
wwb.close();
long end = System.currentTimeMillis();
System.out.println("----完成该操作共用的时间是:"+(end-start)/1000);
} catch (Exception e) {
System.out.println("---出现异常---");
e.printStackTrace();
}
}
}
下载excel表格
public String exportReport(){
accounts = (SysAccounts) getRequest().getSession().getAttribute(
"SYSaccount");
if (!"".equals(accounts) && null!= accounts ) {
String fp = "/report/posquery/";
Long file = (new Date()).getTime();
System.out.print("开始报表下载");
Map map=null;
listmap=new ArrayList<Map>();
List datelist=Dateutil.datelist(ymouse);//得到日期
String hql="from "+Orgbank.class.getName()+" where bankno='"+bankno+"'";
List lists=bankbfjreportService.find(hql);
if(lists!=null&&lists.size()>0){
bankacct=(Orgbank) lists.get(0);
}
System.out.print(sql);
list=bankbfjreportService.getListFromSQL(sql);
Double bbputamt=0.0;
Double bbputfeeamt=0.0;
Double qbputamt=0.0;
Double qbputfeeamt=0.0;
Double bysputamt=0.0;
Double bysputfeeamt=0.0;
Integer trandate1=0;
for(int i=1;i<=datelist.size();i++){
map=new HashMap();
map.put("date", i);
if(list!=null&&list.size()>0){
Object[] obj=null;
int kk=0;
for(int j=0;j<list.size();j++){
if(null!=obj[0]){
String date=obj[0].toString();
date=date.substring(7, 8);
trandate1=Integer.valueOf(date);
}
if(null!=obj[1]){
bbputamt=Double.valueOf(obj[1].toString());
}
if(null!=obj[2]){
bbputfeeamt=Double.valueOf(obj[2].toString());
}
if(null!=obj[3]){
qbputamt=Double.valueOf(obj[3].toString());
}
if(null!=obj[4]){
qbputfeeamt=Double.valueOf(obj[4].toString());
}
if(null!=obj[5]){
bysputamt=Double.valueOf(obj[5].toString());
}
if(null!=obj[6]){
bysputfeeamt=Double.valueOf(obj[6].toString());
}
if(i==trandate1){
kk+=1;
map.put("A01", bbputamt);
map.put("A02", bbputfeeamt);
map.put("A03", qbputamt);
map.put("A04", qbputfeeamt);
map.put("A05", bysputamt);
map.put("A06", bysputfeeamt);
map.put("A07", 0);
map.put("A08", 0);
map.put("A09", 0);
map.put("A10", 0);
map.put("A11", 0);
map.put("A12", 0);
map.put("A13", 0);
map.put("A14", 0);
}
}
if(kk!=1){
map.put("A01", 0);
map.put("A02", 0);
map.put("A03", 0);
map.put("A04", 0);
map.put("A05", 0);
map.put("A06", 0);
map.put("A07", 0);
map.put("A08", 0);
map.put("A09", 0);
map.put("A10", 0);
map.put("A11", 0);
map.put("A12", 0);
map.put("A13", 0);
map.put("A14", 0);
listmap.add(map);
}
}else{
map.put("A01", 0);
map.put("A02", 0);
map.put("A03", 0);
map.put("A04", 0);
map.put("A05", 0);
map.put("A06", 0);
map.put("A07", 0);
map.put("A08", 0);
map.put("A09", 0);
map.put("A10", 0);
map.put("A11", 0);
map.put("A12", 0);
map.put("A13", 0);
map.put("A14", 0);
System.out.println(map.get("date")+"---------------");
listmap.add(map);
}
}
if (listmap.size() > 65000) {
setMessage("<script>alert('所选择日期范围内记录数大于65000条,不允许下载!');location.href='pro.do';</script>");
return ERROR;
}
ZfrjdetailAction ce = new ZfrjdetailAction();
ce.createExcel(bankbfjreportService,ymouse,bankno,getRequest(), listmap, fp, file.toString()
+ ".xls");
String path = fp + file.toString() + ".xls";
try {
HttpServletResponse response = this.getResponse();
response.setCharacterEncoding("UTF-8");
PrintWriter o = response.getWriter();
StringBuffer ou = new StringBuffer();
// ou.append("<script>alert('asdf');location.href='/giftweb/Downlaod'</script>");
ou.append("<script>top.location.href='/giftweb/Downlaod?file="
+ path + "';history.go(-1);</script>");
// ou.append("<script>location.href='/Downlaod?file=/report/posquery/1392729094571.xls';hisory.go(-1);</script>");
System.err.println(ou.toString());
o.write(ou.toString());
o.flush();
o.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
setMessage("<script>alert(\"登陆超时,请重新登陆!\");top.location.href='/giftweb/admin/logining.html';</script>");
return ERROR;
}
return ERROR;
}
设置样式链接:
http://zhouhaitao.iteye.com/blog/1842769