项目说明:  

1:数据库中有两张表,主键关联

2:根据条件查询数据

3:处理为需要的数据封装类型,然后传到导出excel的方法中

<--框架部署就不详谈了,用的spring框架-->

补充:POI详解:http://www.cnblogs.com/huajiezh/p/5467821.html

   POI中设置Excel单元格格式样式(居中,字体,边框,背景色、列宽、合并单元格等) 

直接上代码:首先是数据的获取,这里只上控制层代码,底层就不多说了

导入的包:

import java.io.BufferedOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.hssf.util.HSSFColor;

实体类代码:(导出的类型)

public class ExportDateTest implements Serializable{
private String name;
//private String gender;//性别
private String weight;
//private String grades;//班级
private Double Networkprotocol;
private Double javaEE;
private Double Computerbasis;
private Double Linuxoperatingsystem;
private Double networksecurity;
private Double SQLdatabase;
private Double datastructure;
public ExportDateTest() { // TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
*/
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
/*
public String getGrades() {
return grades;
}
public void setGrades(String grades) {
this.grades = grades;
}
*/
public Double getNetworkprotocol() {
return Networkprotocol;
}
public void setNetworkprotocol(Double networkprotocol) {
Networkprotocol = networkprotocol;
}
public Double getJavaEE() {
return javaEE;
}
public void setJavaEE(Double javaEE) {
this.javaEE = javaEE;
}
public Double getComputerbasis() {
return Computerbasis;
}
public void setComputerbasis(Double computerbasis) {
Computerbasis = computerbasis;
}
public Double getLinuxoperatingsystem() {
return Linuxoperatingsystem;
}
public void setLinuxoperatingsystem(Double linuxoperatingsystem) {
Linuxoperatingsystem = linuxoperatingsystem;
}
public Double getNetworksecurity() {
return networksecurity;
}
public void setNetworksecurity(Double networksecurity) {
this.networksecurity = networksecurity;
}
public Double getSQLdatabase() {
return SQLdatabase;
}
public void setSQLdatabase(Double sQLdatabase) {
SQLdatabase = sQLdatabase;
}
public Double getDatastructure() {
return datastructure;
}
public void setDatastructure(Double datastructure) {
this.datastructure = datastructure;
}
public ExportDateTest(String name, String gender, String weight, String grades, Double networkprotocol, Double javaEE,
Double computerbasis, Double linuxoperatingsystem, Double networksecurity, Double sQLdatabase,
Double datastructure) {
super();
this.name = name;
//this.gender = gender;
this.weight = weight;
//this.grades = grades;
Networkprotocol = networkprotocol;
this.javaEE = javaEE;
Computerbasis = computerbasis;
Linuxoperatingsystem = linuxoperatingsystem;
this.networksecurity = networksecurity;
SQLdatabase = sQLdatabase;
this.datastructure = datastructure;
}
@Override
public String toString() {
return "ExportDate [name=" + name + ""
//+ ", gender=" + gender + ""
+ ", weight=" + weight + ""
// + ", grades=" + grades
+ ", Networkprotocol=" + Networkprotocol + ", javaEE=" + javaEE + ", Computerbasis=" + Computerbasis
+ ", Linuxoperatingsystem=" + Linuxoperatingsystem + ", networksecurity=" + networksecurity
+ ", SQLdatabase=" + SQLdatabase + ", datastructure=" + datastructure + "]";
} }

控制层部分代码:

List<ExportDate> list=expot.GetStudentTest(gender.getGender());// 
System.out.println("listDate:"+list);
//ExportExcelXSSF<ExportDate> ee= new ExportExcelXSSF<ExportDate>();
ExportExcelHSSF<ExportDate> ee= new ExportExcelXSSF<ExportDate>();
ExportExcelOutputStream ee=new ExportExcelOutputStream(); //String[] headers = { "姓名", "性别", "体重","班级","网络协议","javaEE","计算机基础","Linux操作系统","网络安全","sql数据库","数据结构" };
String[] headers = { "姓名","体重","网络协议","javaEE","计算机基础","Linux操作系统","网络安全","sql数据库","数据结构" };
String fileName = "信息表"; System.out.println();
ee.exportExcel(list, headers,fileName, response);

关键的导出代码:

public class ExportExcelHSSFTest<T> {
public void exportExcel(String[] headers,Collection<T> dataset, String fileName,HttpServletResponse response) {
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(fileName);
//样式对象
HSSFCellStyle style=workbook.createCellStyle();
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth(15);
// 产生表格标题行
HSSFRow row = sheet.createRow(0); //设置行高
row.setHeightInPoints(30);//设置行高
for (int i = 0; i < headers.length; i++) {
HSSFCell cell=row.createCell(i);
//设置背景
style.setFillBackgroundColor((short)13);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//设置字体
HSSFFont font2 = workbook.createFont();
font2.setFontName("仿宋_GB2312");
font2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
font2.setFontHeightInPoints((short) 12); //字体大小
font2.setColor(HSSFColor.RED.index);//设置字体颜色
style.setFont(font2);//选择需要用到的字体格式
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellStyle(style);
cell.setCellValue(text);
}
try {
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
T t = (T) it.next();
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
// 判断值的类型后进行强制类型转换
String textValue = null;
// 其它数据类型都当作字符串简单处理
if(value != null && value != ""){
textValue = value.toString();
}
if (textValue != null) {
HSSFRichTextString richString = new HSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
}
getExportedFile(workbook, fileName,response);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* 方法说明: 指定路径下生成EXCEL文件
* @return
*/
public void getExportedFile(HSSFWorkbook workbook, String name,HttpServletResponse response) throws Exception {
System.out.println("name:"+name);
BufferedOutputStream fos = null;
try {
String fileName = name + ".xls";
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ));
fos = new BufferedOutputStream(response.getOutputStream());
workbook.write(fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
System.out.println("ok");
fos.close();
}
}
} }

下一篇:从数据库导出数据到excel之List<Map<String,Object>>

下下篇:从数据库导出数据到excel之List<List<Object>>

从数据库导出数据到excel之POI操作的更多相关文章

  1. 从数据库导出数据到excel之List<List<Object>>导出

    说明:有时候数据处理为List<List<Object>>更方便 姊妹篇:从数据库导出数据到excel之List<Map<>>导出 兄弟篇:从数据库导出 ...

  2. 使用python脚本从数据库导出数据到excel

    python从数据库导出数据到excel 最近需要从数据库里导出一些数据到excel,刚开始我是使用下面的命令 select * from xxx where xxx into outfile 'xx ...

  3. 数据库导出数据到excel格式

    场景: 由于业务人员经常会找DBA导出一些数据,写了一个自动导出脚本. import pymysql from openpyxl import Workbook from openpyxl.write ...

  4. VBA中数据库导出数据到Excel注意事项

    Sub ReadDBData() On Error GoTo ErrorHand Dim dbHelper As New dbHelper Dim sqlSQL As String Dim rs As ...

  5. 从数据库导出数据到excel之List<map>导出

    说明:很多时候取出来的数据是封装为List<Map<String,Object>>,可以直接导出excel表格 项目说明就在 “上一篇” 直接上代码(数据层和业务层不用说了,查 ...

  6. Java导出数据为EXCEL的两种方式JXL和POI

    JXL和POI导出数据方式的比较 POI支持excel2003和2007,而jxl只支持excel2003. 下面为测试代码: public class TestCondition { /** * 生 ...

  7. 手把手教你springboot中导出数据到excel中

    手把手教你springboot中导出数据到excel中 问题来源: 前一段时间公司的项目有个导出数据的需求,要求能够实现全部导出也可以多选批量导出(虽然不是我负责的,我自己研究了研究),我们的项目是x ...

  8. NPOI导出数据到Excel

    NPOI导出数据到Excel   前言 Asp.net操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,使用NPOI能够帮助开发者在没有安装微 ...

  9. ASP.NET导出数据到Excel 实例介绍

    ASP.NET导出数据到Excel  该方法只是把asp.net页面保存成html页面只是把后缀改为xlc不过excel可以读取,接下连我看看还有别的方式能导出数据,并利用模版生成. 下面是代码 新建 ...

随机推荐

  1. HTML符号大全

      HTML特殊字符编码大全:往网页中输入特殊字符,需在html代码中加入以&开头的字母组合或以&#开头的数字.下面就是以字母或数字表示的特殊符号大全.                 ...

  2. Python 输出百分比的两种方式

    Python 输出百分比的两种方式 注: 在python3环境下测试. 方式1:直接使用参数格式化:{:.2%} {:.2%}: 显示小数点后2位 显示小数点后2位: >>> pri ...

  3. binding与属性

    Text="{Binding Path=SearchKeyWord, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 将“源”显 ...

  4. lvs+keepalived+vsftp配置FTP服务器负载均衡

    LVS+Keepalive 实现服务器的负载均衡高可用一.安装两台机器的安装是一样的,这里只记录一遍.1. 下载LVS+Keepalive 所需安装包http://www.keepalived.org ...

  5. Ubuntu下配置舒服的Python开发环境

    Ubuntu 提供了一个良好的 Python 开发环境,但如果想使我们的开发效率最大化,还需要进行很多定制化的安装和配置.下面的是我们团队开发人员推荐的一个安装和配置步骤,基于 Ubuntu 12.0 ...

  6. C++复习4.函数设计基础

    C/C++ 函数设计基础 20130918 函数式程序的基本功能单元,是模块化程序设计的基础,即使函数的功能正确是不够的,因为函数设计的细微缺点很容易导致函数被错用. 了解函数的基本知识,堆栈和堆的相 ...

  7. 【HTML5】HTML5 WebSocket简介以及简单示例

    互联网发展到现在,早已超越了原始的初衷,人类从来没有像现在这样依赖过他:也正是这种依赖,促进了互联网技术的飞速发展.而终端设备的创新与发展,更加速了互联网的进化: HTTP/1.1规范发布于1999年 ...

  8. Java基础学习-Collection体系结构和迭代测试

    package Collection; import java.util.ArrayList; import java.util.Collection; import java.util.Iterat ...

  9. (转)MapReduce Design Patterns(chapter 4 (part 2))(八)

    Binning Pattern Description 分箱模式,跟前面的类似,分类记录且不考虑记录的顺序. Intent 归档数据集中的每条记录到一个或多个类别. Motivation 分箱和分区很 ...

  10. v-if和v-show小对比

    相同点 都可以控制元素的显示与不显示.在判断DOM节点是否要显示. 不同点 1.实现方式 v-if是根据后面的数据的真假判断直接从DOM树上删除或重建元素节点. v-show 只是修改元素的css的样 ...