java使用POI,以excel文件的形式,导出前端表格数据

知识点:前端表格数据,调用后台接口,导出excel文件数据,使用到Apache POI接口

POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

(1)在pom.xml中引入POI和文件读写相关的包

<dependency>    <groupId>commons-io</groupId>    <artifactId>commons-io</artifactId></dependency>

<dependency>    <groupId>org.apache.poi</groupId>    <artifactId>poi-ooxml</artifactId></dependency>

(2)Controller层,表格导出接口

/** * 导出数据 */@RequestMapping("/Export")public void export(HttpServletRequest request,HttpServletResponse response){    Export<Equipment> ee = new Export<Equipment>();//equipment实体类    List<Equipment> equiplist = equipmentService.getEquipmentList();  //equiplist是查询的数据集合    String [] headers = {"e_id","e_code","e_location","e_ip","e_attend_code","cruser","crtime","upuser","uptime"};//表格头数据设置    String fileName = "设备列表数据"; //excel表格名称    response.setContentType("application/x-msdownload");   ServletOutputStream outputStream = null;  //outputStream文件输出流    try    {        fileName = fileName + ".xls";// 定义文件格式         if (request.getHeader("USER-AGENT").toLowerCase().contains("firefox"))// 火狐        {            response.setHeader("Content-Disposition",                    "attachment;fileName=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));        }        else        {            response.setHeader("Content-Disposition",                    "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));        }        outputStream = response.getOutputStream();        try {            ee.Export(headers, fileName, equiplist, outputStream);//表格导出工具类        } catch (InvocationTargetException e) {            e.printStackTrace();        }    }    catch (UnsupportedEncodingException e)    {        throw new BusinessException("导出失败!");    }    catch (IOException e)    {        throw new BusinessException("导出失败!");    }    catch (NoSuchMethodException e)    {        LOGGER.error(e.getMessage());    }    catch (IllegalAccessException e)    {        LOGGER.error(e.getMessage());    } finally    {        IOUtils.closeQuietly(outputStream);//    }}

(3)Export.java 表格导出工具类
package com.agesun.attendance.common;import java.io.OutputStream;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.Iterator;import java.util.List;

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.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/** * <一句话功能简述> <功能详细描述> * * @author nishuai * @version [版本号, 2018年06月14日] * @see [相关类/方法] * @since [产品/模块版本] */public class Export<T>{    public void Export(String[] headers, String fileName, List<T> dataset, OutputStream outputStream)        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException    {        // 声明一个工作薄        HSSFWorkbook wb = new HSSFWorkbook();        // 声明一个单子并命名        HSSFSheet sheet = wb.createSheet(fileName);

/****************** 头部样式 ***********************/        HSSFFont font = wb.createFont();        font.setFontName("微软雅黑");        font.setFontHeightInPoints((short)14);// 设置字体大小        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);        // 给单子名称一个长度        sheet.setDefaultColumnWidth((short)16);        // 生成一个样式        HSSFCellStyle style = wb.createCellStyle();        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中        style.setFont(font);        /********************* 数据单元格样式 **************************/        HSSFFont rowFont = wb.createFont();        rowFont.setFontName("宋体");        rowFont.setFontHeightInPoints((short)14);// 设置字体大小        // 给单子名称一个长度        sheet.setDefaultColumnWidth((short)16);        // 生成一个样式        HSSFCellStyle rowStyle = wb.createCellStyle();        rowStyle.setFont(rowFont);        // 样式字体居中        rowStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

// 创建第一行(也可以称为表头)        HSSFRow row = sheet.createRow(0);        row.setHeight((short)500);        // 给表头第一行一次创建单元格        for (short i = 0; i < headers.length; i++)        {            HSSFCell cell = row.createCell(i);            cell.setCellValue(headers[i]);            cell.setCellStyle(style);        }

// 遍历集合数据,产生数据行        Iterator<T> it = dataset.iterator();        int index = 0;        while (it.hasNext())        {            index++;            row = sheet.createRow(index);            row.setHeight((short)500);            T t = it.next();            // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值              Field[] fields = t.getClass().getDeclaredFields();        for (short i = 0; i < headers.length; 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 && !"".equals(value))        {            textValue = value.toString();        }        if (textValue != null)        {            HSSFCell cell = row.createCell(i);            cell.setCellStyle(rowStyle);            cell.setCellValue(textValue);        }    }}

原文地址:https://www.cnblogs.com/shuaifing/p/9184243.html

时间: 2024-08-05 01:53:52

java使用POI,以excel文件的形式,导出前端表格数据的相关文章

java使用POI操作excel文件,实现批量导出,和导入

一.POI的定义 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作Excel 95及以后的版本,即可操作后缀为 .xls 和 .xlsx两种格式的excel. POI全称 Poor Obfuscation Implementation,直译为"可怜的模糊实现",利用POI接口可以通过JAVA操作Microsoft office 套件工具的读写功能.官网:htt

java使用POI实现excel文件的读取,兼容后缀名xls和xlsx

需要用的jar包如下: 如果是maven管理的项目,添加依赖如下: <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version> </depen

java 利用 poi 生成 Excel文件的例子

在用java 写数据库应用的时候, 通常会生成各种报表,而这些报表可能会被导出为各种格式的文件,比如Excel文档,pdf 文档等等. 今天先做了一个生成Excel 文档的例子,主要解决以下问题: 1. 生成 Excel 文档. 2. 保护生成Excel文档,设置密码访问. 3. 自动对生成的Excel 文档第一行标题栏设置成filter 过滤形式, 方便用户使用. 用 apache  POI 生成 Excel 文档公用类  程序代码 package com.yihaomen.poi.sampl

java使用POI写Excel文件

参考地址:http://www.cnblogs.com/xwdreamer/archive/2011/07/20/2296975.html 1 jar包 网上下载 2 源代码 package zjr.amy.excel; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java

java使用poi生成Excel文件

1. maven导入poi包: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> pom.xml 2. 新建测试数据实体类: package com.clz.testexportexcel; public class Exc

java利用poi读取Excel文件

java读取Excel文件,笔者认为:从结构上来看,Excel文件是由一个一个的单元格组成的,有点像细胞cell,逐行的排列.那么我们读的时候也应该逐行逐行的读,从左到右的寻找每一个cell.一.实例代码: 只是实现了一种方式,因为依照读取内容的不同,读取的后想要的操作不同,因此不能苟同全部,只是方法是相通的.说道Excel文件的结构,这货从数学的角度来说,绝对是一个二维数组,因此我就拿字符串二维数组接受读取后的内容,并每个单元格每个单元格的打印.当然也可以返回三维数组(包含该单元格的位置坐标)

java使用poi自定义excel标题头并导出(springmvc+poi)

项目使用的是jeecg开源框架(springmvc+spring+hibernate+......等)此代码仅供参考!如有更好的意见或建议可留言. 1 controller 层 2 3 /** 4 * excel自定义导出 5 * @param hAqscTieupsummary 6 * @param request 7 * @param response 8 * @param dataGrid 9 * @param modelMap 10 * @return 11 */ 12 @Suppres

java使用poi创建excel文件

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.poifs.filesystem.POIFSFileSystem; 注:此方法创

java利用poi解析excel文件

首先需要引入以下jar包 如果使用maven,需要添加两个依赖 <dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.ap