package com.cxy.domain.poi;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelAttribute {
/** 对应的列名称 */
String name() default ""; /** excel列的索引 */
int sort(); /** 字段类型对应的格式 */
String format() default "";
}
package com.ihrm.common.poi;

import com.ihrm.domain.poi.ExcelAttribute;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; /**
* 导出Excel工具类
* 基于模板打印的方式导出:
*/
@Getter
@Setter
public class ExcelExportUtil<T> { private int rowIndex; //写入数据的起始行
private int styleIndex; //需要提取的样式所在的行号
private Class clazz; //对象的字节码
private Field fields[]; //对象中的所有属性 public ExcelExportUtil(Class clazz,int rowIndex,int styleIndex) {
this.clazz = clazz;
this.rowIndex = rowIndex;
this.styleIndex = styleIndex;
fields = clazz.getDeclaredFields();
} /**
* 基于注解导出
参数:
response:
InputStream:模板的输入流
objs:数据
fileName:生成的文件名
*
*/
public void export(HttpServletResponse response,InputStream is, List<T> objs,String fileName) throws Exception { //1.根据模板创建工作簿
XSSFWorkbook workbook = new XSSFWorkbook(is);
//2.读取工作表
Sheet sheet = workbook.getSheetAt();
//3.提取公共的样式
CellStyle[] styles = getTemplateStyles(sheet.getRow(styleIndex));
//4.根据数据创建每一行和每一个单元格的数据2
AtomicInteger datasAi = new AtomicInteger(rowIndex); //数字
for (T t : objs) {
//datasAi.getAndIncrement() :获取数字,并++ i++
Row row = sheet.createRow(datasAi.getAndIncrement());
for(int i=;i<styles.length;i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(styles[i]);
for (Field field : fields) {
if(field.isAnnotationPresent(ExcelAttribute.class)){
field.setAccessible(true);
ExcelAttribute ea = field.getAnnotation(ExcelAttribute.class);
if(i == ea.sort()) {
if(field.get(t) != null) {
cell.setCellValue(field.get(t).toString());
}
}
}
}
}
}
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("ISO8859-1")));
response.setHeader("filename", fileName);
workbook.write(response.getOutputStream());
} public CellStyle[] getTemplateStyles(Row row) {
CellStyle [] styles = new CellStyle[row.getLastCellNum()];
for(int i=;i<row.getLastCellNum();i++) {
styles[i] = row.getCell(i).getCellStyle();
}
return styles;
}
}
package com.ihrm.common.poi;

import com.ihrm.domain.poi.ExcelAttribute;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.format.CellFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; public class ExcelImportUtil<T> { private Class clazz;
private Field fields[]; public ExcelImportUtil(Class clazz) {
this.clazz = clazz;
fields = clazz.getDeclaredFields();
} /**
* 基于注解读取excel
*/
public List<T> readExcel(InputStream is, int rowIndex,int cellIndex) {
List<T> list = new ArrayList<T>();
T entity = null;
try {
XSSFWorkbook workbook = new XSSFWorkbook(is);
Sheet sheet = workbook.getSheetAt();
// 不准确
int rowLength = sheet.getLastRowNum(); System.out.println(sheet.getLastRowNum());
for (int rowNum = rowIndex; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
entity = (T) clazz.newInstance();
System.out.println(row.getLastCellNum());
for (int j = cellIndex; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
for (Field field : fields) {
if(field.isAnnotationPresent(ExcelAttribute.class)){
field.setAccessible(true);
ExcelAttribute ea = field.getAnnotation(ExcelAttribute.class);
if(j == ea.sort()) {
field.set(entity, covertAttrType(field, cell));
}
}
}
}
list.add(entity);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
} /**
* 类型转换 将cell 单元格格式转为 字段类型
*/
private Object covertAttrType(Field field, Cell cell) throws Exception {
String fieldType = field.getType().getSimpleName();
if ("String".equals(fieldType)) {
return getValue(cell);
}else if ("Date".equals(fieldType)) {
return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(getValue(cell)) ;
}else if ("int".equals(fieldType) || "Integer".equals(fieldType)) {
return Integer.parseInt(getValue(cell));
}else if ("double".equals(fieldType) || "Double".equals(fieldType)) {
return Double.parseDouble(getValue(cell));
}else {
return null;
}
} /**
* 格式转为String
* @param cell
* @return
*/
public String getValue(Cell cell) {
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case STRING:
return cell.getRichStringCellValue().getString().trim();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
Date dt = DateUtil.getJavaDate(cell.getNumericCellValue());
return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(dt);
} else {
// 防止数值变成科学计数法
String strCell = "";
Double num = cell.getNumericCellValue();
BigDecimal bd = new BigDecimal(num.toString());
if (bd != null) {
strCell = bd.toPlainString();
}
// 去除 浮点型 自动加的 .0
if (strCell.endsWith(".0")) {
strCell = strCell.substring(, strCell.indexOf("."));
}
return strCell;
}
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
default:
return "";
}
}
}
package com.ihrm.common.utils;

import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; public class DownloadUtils {
public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException {
response.setContentType("application/octet-stream");
returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1")); //保存的文件名,必须和页面编码一致,否则乱码
response.addHeader("content-disposition","attachment;filename=" + returnName);
response.setContentLength(byteArrayOutputStream.size());
ServletOutputStream outputstream = response.getOutputStream(); //取得输出流
byteArrayOutputStream.writeTo(outputstream); //写到输出流
byteArrayOutputStream.close(); //关闭
outputstream.flush(); //刷数据
}
}
  @RequestMapping(value = "/export/{month}", method = RequestMethod.GET)
public void export(@PathVariable String month) throws Exception {
//1.获取报表数据
List<EmployeeReportResult> list = userCompanyPersonalService.findByReport(companyId,month);
//2.构造Excel
//创建工作簿
//SXSSFWorkbook : 百万数据报表
//Workbook wb = new XSSFWorkbook();
SXSSFWorkbook wb = new SXSSFWorkbook(); //阈值,内存中的对象数量最大数量
//构造sheet
Sheet sheet = wb.createSheet();
//创建行
//标题
String [] titles = "编号,姓名,手机,最高学历,国家地区,护照号,籍贯,生日,属相,入职时间,离职类型,离职原因,离职时间".split(",");
//处理标题
Resource resource = new ClassPathResource("excel-template/hr-demo.xlsx");
Row row = sheet.createRow(); int titleIndex=;
for (String title : titles) {
Cell cell = row.createCell(titleIndex++);
cell.setCellValue(title);
} int rowIndex = ;
Cell cell=null;
for(int i=;i<;i++){
for (EmployeeReportResult employeeReportResult : list) {
row = sheet.createRow(rowIndex++);
// 编号,
cell = row.createCell();
cell.setCellValue(employeeReportResult.getUserId());
// 姓名,
cell = row.createCell();
cell.setCellValue(employeeReportResult.getUsername());
// 手机,
cell = row.createCell();
cell.setCellValue(employeeReportResult.getMobile());
// 最高学历,
cell = row.createCell();
cell.setCellValue(employeeReportResult.getTheHighestDegreeOfEducation());
// 国家地区,
cell = row.createCell();
cell.setCellValue(employeeReportResult.getNationalArea());
// 护照号,
cell = row.createCell();
cell.setCellValue(employeeReportResult.getPassportNo());
// 籍贯,
cell = row.createCell();
cell.setCellValue(employeeReportResult.getNativePlace());
// 生日,
cell = row.createCell();
cell.setCellValue(employeeReportResult.getBirthday());
// 属相,
cell = row.createCell();
cell.setCellValue(employeeReportResult.getZodiac());
// 入职时间,
cell = row.createCell();
cell.setCellValue(employeeReportResult.getTimeOfEntry());
// 离职类型,
cell = row.createCell();
cell.setCellValue(employeeReportResult.getTypeOfTurnover());
// 离职原因,
cell = row.createCell();
cell.setCellValue(employeeReportResult.getReasonsForLeaving());
// 离职时间
cell = row.createCell();
cell.setCellValue(employeeReportResult.getResignationTime());
}
}
//3.完成下载
ByteArrayOutputStream os = new ByteArrayOutputStream();
wb.write(os);
new DownloadUtils().download(os,response,month+"人事报表.xlsx");
} /**
* 采用模板打印的形式完成报表生成
* 模板
* 参数:
* 年月-月(2018-02%)
*
* sxssf对象不支持模板打印
*/
// @RequestMapping(value = "/export/{month}", method = RequestMethod.GET)
// public void export(@PathVariable String month) throws Exception {
// //1.获取报表数据
// List<EmployeeReportResult> list = userCompanyPersonalService.findByReport(companyId,month);
//
// //2.加载模板
// Resource resource = new ClassPathResource("excel-template/hr-demo.xlsx");
// FileInputStream fis = new FileInputStream(resource.getFile());
//
// //3.通过工具类完成下载
//// new ExcelExportUtil(EmployeeReportResult.class,2,2).
//// export(response,fis,list,month+"人事报表.xlsx");
//
//
// //3.根据模板创建工作簿
// Workbook wb = new XSSFWorkbook(fis);
// //4.读取工作表
// Sheet sheet = wb.getSheetAt(0);
// //5.抽取公共样式
// Row row = sheet.getRow(2);
// CellStyle styles [] = new CellStyle[row.getLastCellNum()];
// for(int i=0;i<row.getLastCellNum();i++) {
// Cell cell = row.getCell(i);
// styles[i] = cell.getCellStyle();
// }
// //6.构造单元格
// int rowIndex = 2;
// Cell cell=null;
// for(int i=0;i<10000;i++) {
// for (EmployeeReportResult employeeReportResult : list) {
// row = sheet.createRow(rowIndex++);
// // 编号,
// cell = row.createCell(0);
// cell.setCellValue(employeeReportResult.getUserId());
// cell.setCellStyle(styles[0]);
// // 姓名,
// cell = row.createCell(1);
// cell.setCellValue(employeeReportResult.getUsername());
// cell.setCellStyle(styles[1]);
// // 手机,
// cell = row.createCell(2);
// cell.setCellValue(employeeReportResult.getMobile());
// cell.setCellStyle(styles[2]);
// // 最高学历,
// cell = row.createCell(3);
// cell.setCellValue(employeeReportResult.getTheHighestDegreeOfEducation());
// cell.setCellStyle(styles[3]);
// // 国家地区,
// cell = row.createCell(4);
// cell.setCellValue(employeeReportResult.getNationalArea());
// cell.setCellStyle(styles[4]);
// // 护照号,
// cell = row.createCell(5);
// cell.setCellValue(employeeReportResult.getPassportNo());
// cell.setCellStyle(styles[5]);
// // 籍贯,
// cell = row.createCell(6);
// cell.setCellValue(employeeReportResult.getNativePlace());
// cell.setCellStyle(styles[6]);
// // 生日,
// cell = row.createCell(7);
// cell.setCellValue(employeeReportResult.getBirthday());
// cell.setCellStyle(styles[7]);
// // 属相,
// cell = row.createCell(8);
// cell.setCellValue(employeeReportResult.getZodiac());
// cell.setCellStyle(styles[8]);
// // 入职时间,
// cell = row.createCell(9);
// cell.setCellValue(employeeReportResult.getTimeOfEntry());
// cell.setCellStyle(styles[9]);
// // 离职类型,
// cell = row.createCell(10);
// cell.setCellValue(employeeReportResult.getTypeOfTurnover());
// cell.setCellStyle(styles[10]);
// // 离职原因,
// cell = row.createCell(11);
// cell.setCellValue(employeeReportResult.getReasonsForLeaving());
// cell.setCellStyle(styles[11]);
// // 离职时间
// cell = row.createCell(12);
// cell.setCellValue(employeeReportResult.getResignationTime());
// cell.setCellStyle(styles[12]);
// }
// }
// //7.下载
// //3.完成下载
// ByteArrayOutputStream os = new ByteArrayOutputStream();
// wb.write(os);
// new DownloadUtils().download(os,response,month+"人事报表.xlsx");
// }
}

注解到处excel的更多相关文章

  1. 反射+自定义注解---实现Excel数据列属性和JavaBean属性的自动映射

    简单粗暴,直奔主题.   需求:通过自定义注解和反射技术,将Excel文件中的数据自动映射到pojo类中,最终返回一个List<pojo>集合? 今天我只是通过一位使用者的身份来给各位分享 ...

  2. js到处excel

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...

  3. importExcel运用注解实现EXCEL导入poi类

    JAVA报表 package com.app.common.excel; import java.io.File; import java.io.FileInputStream; import jav ...

  4. silverlight中datagrid数据到处excel

    首先新建一个DataGrdiExtensions类,代码为: public static class DataGridExtensions { /// <summary> /// 导出dg ...

  5. webapi到处excel

    最近项目用的webapi前几天做了个导出excel功能,给大家分享下,自己也记录下... 在用的过程中,可以直接请求就可以得到下载的excel文件,在实际的项目中可以通过js打开新页面,encodeU ...

  6. 170313、poi:采用自定义注解的方式导入、导出excel(这种方式比较好扩展)

    步骤一.自定义注解 步骤二.写Excel泛型工具类 步骤三.在需要导出excel的类属相上加上自定义注解,并设置 步骤四.写service,controller 步骤一:自定义注解 import ja ...

  7. java通过注解指定顺序导入excel

    自定义的属性,用来判断顺序的 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; impor ...

  8. c#使用Microsoft Excel 12.0 object Libary导出的Excel文件office2003不能打开!!~~(分享)

    -----转载:http://hi.baidu.com/zhang_zhu_1/item/f3d47d1f86bf037a70d5e87e 使用C#导出数据到Excel文件时,Excel 2007组件 ...

  9. PowerDesigner 中模型设计导出Excel表格

    今天项目做设计,客户要看数据设计,需要到处Excel表格.去网上搜索下,把使用总结如下: 已经完成设计的pd设计 打开pd,快捷键Ctrl + Shift + X或者Tools>Exectue ...

随机推荐

  1. Python 中练习题涉及到的无穷大和无穷小问题。

    首先来看一下所见的python联系题. inf = infinite 无限制的 float("inf")-1执行后的结果是:() A 1 B inf C -inf D 0 该考点考 ...

  2. thinkphp5选择redis库,让数据存入不同的redis库

    thinkphp5选择redis库,让数据存入不同的redis库 在登录的时候把个人信息存入redis,选择redis库1号库, db1 读取redis里面的个人信息

  3. 【Java多线程系列六】Map实现类

    Map的一些实现类有及其特性 类 线程安全 特性 Hashtable 是 Key不能为null HashMap 否 读写效率最高,但在Java6多线程环境下使用不当可能陷入死循环,进而导致CPU使用率 ...

  4. JS中的事件、数组、节点对象处理

    在JS代码中编写事件一定要保证页面在浏览器中加载时会把事件加载进页面 事件:在代码中可以通过一个动作来触发另一个行为的总称 A:事件的编写方式1 HTML标签中添加 onxxxx = "函数 ...

  5. 一、数据库、SQL简介

    1.数据库简介 1.1数据库:保存有组织的数据的容器(通常是一个文件或一组文件) 数据库软件:称为数据库管理系统(DBMS),数据库是通过DBMS创建和操纵的.通常用户使用DBMS访问数据库. 表:表 ...

  6. 爬虫抓取5大门户网站和电商数据day1:基础环境搭建

    最新想用爬虫实现抓取五大门户网站(搜狐.新浪.网易.腾讯.凤凰网)和电商数据(天猫,京东,聚美等), 今天第一天先搭建下环境和测试. 采用maven+xpath+ HttpClient+正则表达式. ...

  7. C# WinfForm 控件之dev报表 XtraReport (四) 动态绑定主从关系表

    一般的单据都是由主从关系的,比如部门与人员.单据表头与表身.仓库与存货.分类与档案等等 所以主从关系是报表用的最多的 1.准备数据库 简单方便 --主表 create table RdRecord ( ...

  8. java-day26

    ## DOM简单学习:为了满足案例要求     * 功能:控制html文档的内容     * 获取页面标签(元素)对象:Element         * document.getElementByI ...

  9. Xn数列

     题目描述 Description 给你6个数,m, a, c, x0, n, g Xn+1 = ( aXn + c ) mod m,求Xn m, a, c, x0, n, g<=10^18 输 ...

  10. cmake 支持-lpthread

    set(CMAKE_BUILD_TYPE "Release") if( CMAKE_BUILD_TYPE STREQUAL "Debug" )    set(C ...