最近在项目开发中遇到这样一个需求,用户聊天模块产品要求记录用户聊天信息,但只保存当天的,每天都要刷新清空数据,但聊天记录要以Excel的形式打印出来,于是就引出了将数据库的数据导出成Excel表格的需求。直奔主题。

  在java中其实已经有了封装好的jar包,我们这里只要导入相应的jar包即可,具体如下(忘了是那几个了,所以就全截图了=_=)

  然后就是工具类,代码如下:

  

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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExportExcelUtil<T> { public void exportExcel(String[] headers,Collection<T> dataset, String fileName,HttpServletResponse response) {
// 声明一个工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
// 生成一个表格
XSSFSheet sheet = workbook.createSheet(fileName);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 20);
// 产生表格标题行
XSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++) {
XSSFCell cell = row.createCell(i);
XSSFRichTextString text = new XSSFRichTextString(headers[i]);
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 (short i = 0; i < headers.length; i++) {
XSSFCell 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) {
XSSFRichTextString richString = new XSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
}
getExportedFile(workbook, fileName,response);
} catch (Exception e) {
e.printStackTrace();
}
} /**
*
* 方法说明: 指定路径下生成EXCEL文件
* @return
*/
public void getExportedFile(XSSFWorkbook workbook, String name,HttpServletResponse response) throws Exception {
BufferedOutputStream fos = null;
try {
String fileName = name + ".xlsx";
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) {
fos.close();
}
}
} }

  在使用时,调用如下:(我这里是使用的springMVC,所以直接写在了接口中,为了省事就全部截取了~_~)

    /**
* 导出数据库
* @param response
*/
@RequestMapping(value="exportExcel.do",method=RequestMethod.GET,
produces="application/json;charset=utf-8")
@ResponseBody
public void exportExcel(HttpServletResponse response){
Map<String, Object> map = new HashMap<String, Object>();
map = msgService.findAllMsg();
List<Msg> msgList = (List<Msg>) map.get("data");
ExportExcelUtil<Msg> ee= new ExportExcelUtil<Msg>();
String[] headers = { "序号", "发送用户", "接收用户", "时间" ,"聊天信息"};
String fileName = "用户聊天信息表";
ee.exportExcel(headers,msgList,fileName,response);
}

至此,将数据库信息导出成Excel表格的功能就实现了。

数据库数据生成Excel表格(多用在导出数据)的更多相关文章

  1. Java操作Jxl实现导出数据生成Excel表格数据文件

    实现:前台用的框架是Easyui+Bootstrap结合使用,需要引入相应的Js.Css文件.页面:Jsp.拦截请求:Servlet.逻辑处理:ClassBean.数据库:SQLserver. 注意: ...

  2. 详解python操作生成excel表格,并且填充数据

    最近在研究python操作excel表格的问题,首先读取excel表格觉得平时用的多,不怎么有难度,就是pyhon生成excel表格的时候,平时不怎么用,所以重点研究了一下,现总结如下: 1.首先用到 ...

  3. Java使用poi从数据库读取数据生成Excel表格

    想要使用POI操作以xsl结尾的Excel,首先要下载poi相关的jar包,用到的jar有: poi-3.9.jar poi-ooxml-3.9.jar poi-ooxml-schemas-3.9.j ...

  4. Java导出数据生成Excel表格

    事先准备: 工具类: package com.wazn.learn.util.export; import java.sql.Connection; import java.sql.DriverMan ...

  5. 导出数据到Excel表格

    开发工具与关键技术:Visual Studio 和 ASP.NET.MVC,作者:陈鸿鹏撰写时间:2019年5月25日123下面是我们来学习的导出数据到Excel表格的总结首先在视图层写导出数据的点击 ...

  6. Python导出数据到Excel表格-NotImplementedError: formatting_info=True not yet implemented

    在使用Python写入数据到Excel表格中时出现报错信息记录:“NotImplementedError: formatting_info=True not yet implemented” 报错分析 ...

  7. 将Highcharts图表数据生成Table表格

    有的时候,我们不仅仅需要漂亮的统计图来显示统计结果,还需要在统计图下方一个表格可以更加直观的展现各类数据.既然统计图都显示出来了,那我们可以根据统计图的各元素生成表格了. 首先,先显示统计图. Htm ...

  8. H5纯前端生成Excel表格

    H5纯前端生成Excel表格方法如下: <!DOCTYPE html> <html> <head> <title></title> < ...

  9. php动态导出数据成Excel表格

    一.封装 Excel 导出类 include/components/ExecExcel.php <?php /*** * @Excel 导入导出类. */ class ExecExcel { / ...

随机推荐

  1. Linux - /bin/sh^M: bad interpreter: No such file or directory

    问题 在Windows环境下用Notepad++写了个shell脚本,上传到Linux平台后运行报错如下: /bin/sh^M: bad interpreter: No such file or di ...

  2. (转)hive调优(1) coding调优

    hive 调优(一)coding调优 本人认为hive是很好的工具,目前支持mr,tez,spark执行引擎,有些大公司原来封装的sparksql,开发py脚本,但是目前hive支持spark引擎(不 ...

  3. 国内Archlinux arm的镜像源

    清华 http://mirrors.tuna.tsinghua.edu.cn/archlinuxarm/arch/arch/repo 中科大 http://mirrors.ustc.edu.cn/ar ...

  4. 爬虫界的福利--touchRobot,机器模拟触碰滑动库(已开源)

    此插件能干什么? 一句话概括:通过程序主动触发移动端滑动.拖拽.触碰等操作 插件有什么用呢? 可以用于爬虫,也可以用于自动化测试以及程序演示 插件演示地址 (从网上扒了一个canvas绘图的demo, ...

  5. Spring家族主流成员介绍

    摘 要:Spring 就像一个大家族,有众多衍生产品例如 Boot,Security,JPA等等.但他们的基础都是Spring 的 IOC 和 AOP,IOC提供了依赖注入的容器,而AOP解决了面向切 ...

  6. unittest 的用法

    一.discover方法 discover方法可以根据标准加载用例,并将结果返回给测试套件(suite),start_dir:待测试的目录,pattern:测试用例文件名的匹配规. 如: start_ ...

  7. OpenJudge计算概论-骑车与走路

    /*============================================================ 骑车与走路 总时间限制: 1000ms 内存限制: 65536kB 描述 ...

  8. 【源码】openresty 限流

    小结: 1.在连接环节计数,有清零环节 有3个参量 maxburst unit_delay https://github.com/openresty/lua-resty-limit-traffic/b ...

  9. excel_vlookup函数_python代码实现

    python入门经典视频系列教程(免费,2K超清,送书) https://study.163.com/course/courseMain.htm?courseId=1006183019&sha ...

  10. Assertion failure in -[UISectionRowData refreshWithSection:tableView:tableViewRowData:]

    最近在项目中遇到了 Assertion failure in -[UISectionRowData refreshWithSection:tableView:tableViewRowData:] 这个 ...