之前有写过一点关于java实现写Excel文件的方法,但是现在看来,那种方式用起来不是太舒服,还很麻烦。所以最近又参考其他,就写了一个新版,用起来不要太爽。

代码不需要解释,惯例直接贴下来:

 public class ExcelExport implements Closeable {

     private static final Logger LOGGER = LoggerFactory.getLogger(ExcelExport.class);

     public static final String EXCEL_SUFFIX = ".xlsx"; // 目前只支持xlsx格式

     private static final String SHEET_FONT_TYPE = "Arial";

     private Workbook workbook;

     private Sheet sheet;

     private int rowNum;

     private Map<String, CellStyle> styles;

     private List<ColumnField> columns;

     public ExcelExport createSheet(String sheetName, String title, Class<?> clazz) throws Exception {
this.workbook = createWorkbook();
this.columns = createColumns();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
ExcelField excelField = field.getAnnotation(ExcelField.class);
if (excelField != null) {
this.columns.add(new ColumnField(excelField.title(), field.getName(), field.getType(), excelField.width()));
}
}
if (CollectionUtils.isEmpty(this.columns)) throw new Exception("Excel's headerList are undefined");
this.sheet = workbook.createSheet(StringUtils.defaultString(sheetName, StringUtils.defaultString(title, "Sheet1")));
this.styles = createStyles(workbook);
this.rowNum = 0;
if (StringUtils.isNotBlank(title)) {
Row titleRow = sheet.createRow(rowNum++);
titleRow.setHeightInPoints(30);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellStyle(styles.get("title"));
titleCell.setCellValue(title);
sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(),
this.columns.size() - 1));
}
Row headerRow = sheet.createRow(rowNum++);
headerRow.setHeightInPoints(16);
for (int i = 0; i < this.columns.size(); i++) {
int width = this.columns.get(i).width;
this.sheet.setColumnWidth(i, 256 * width + 184);
Cell cell = headerRow.createCell(i);
cell.setCellStyle(styles.get("header"));
cell.setCellValue(this.columns.get(i).title);
}
return this;
} public <E> ExcelExport setDataList(List<E> dataList) throws IllegalAccessException {
for (E data : dataList) {
int column = 0;
Row row = this.addRow();
Map<String, Object> map = toMap(data);
for (ColumnField field : this.columns) {
Class<?> paramType = field.getParamType();
if (map.containsKey(field.getParam())) {
Object value = map.get(field.getParam());
this.addCell(row, column++, value, paramType);
}
}
}
LOGGER.debug("add data into {} success", this.sheet.getSheetName());
return this;
} private Cell addCell(Row row, int column, Object value, Class<?> type) {
Cell cell = row.createCell(column);
if (value == null) {
cell.setCellValue("");
} else if (type.isAssignableFrom(String.class)) {
cell.setCellValue((String) value);
} else if (type.isAssignableFrom(Integer.class)) {
cell.setCellValue((Integer) value);
} else if (type.isAssignableFrom(Double.class)) {
cell.setCellValue((Double) value);
} else if (type.isAssignableFrom(Long.class)) {
cell.setCellValue((Long) value);
} else if (type.isAssignableFrom(Float.class)) {
cell.setCellValue((Float) value);
} else if (type.isAssignableFrom(Date.class)) {
Date time = (Date) value;
String timer = DateUtils.formatDate(time, "yyyy-MM-dd HH:mm:ss");
cell.setCellValue(timer);
} else {
cell.setCellValue(Objects.toString(value));
}
cell.setCellStyle(styles.get("data"));
return cell;
} private Map<String, Object> toMap(Object entity) throws IllegalAccessException {
Map<String, Object> row = Maps.newHashMap();
if (null == entity) return row;
Class clazz = entity.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
row.put(field.getName(), field.get(entity));
}
return row;
} private Row addRow() {
return sheet.createRow(rowNum++);
} public ExcelExport write(OutputStream os) {
try {
workbook.write(os);
} catch (IOException ex) {
LOGGER.error(ex.getMessage(), ex);
} finally {
if (null != os) {
try {
os.close();
} catch (IOException e) {
LOGGER.error("close Output Stream failed: {}", e.getMessage());
}
}
}
return this;
} public ExcelExport write(HttpServletResponse response, String fileName) {
response.reset();
try {
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, UTF8));
write(response.getOutputStream());
} catch (IOException ex) {
LOGGER.error(ex.getMessage(), ex);
}
return this;
} public ExcelExport writeFile(String name) throws IOException {
FileOutputStream os = new FileOutputStream(name);
this.write(os);
return this;
} private Workbook createWorkbook() {
return new SXSSFWorkbook();
} private List<ColumnField> createColumns() {
return Lists.newLinkedList();
} private Map<String, CellStyle> createStyles(Workbook workbook) {
Map<String, CellStyle> styleMap = Maps.newHashMap(); CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
Font titleFont = workbook.createFont();
titleFont.setFontName(SHEET_FONT_TYPE);
titleFont.setFontHeightInPoints((short) 16);
titleFont.setBold(true);
style.setFont(titleFont);
styleMap.put("title", style); style = workbook.createCellStyle();
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
Font dataFont = workbook.createFont();
dataFont.setFontName(SHEET_FONT_TYPE);
dataFont.setFontHeightInPoints((short) 10);
style.setFont(dataFont);
styleMap.put("data", style); style = workbook.createCellStyle();
style.cloneStyleFrom(styleMap.get("data"));
style.setWrapText(true);
style.setAlignment(HorizontalAlignment.CENTER);
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Font headerFont = workbook.createFont();
headerFont.setFontName(SHEET_FONT_TYPE);
headerFont.setFontHeightInPoints((short) 10);
headerFont.setBold(true);
headerFont.setColor(IndexedColors.WHITE.getIndex());
style.setFont(headerFont);
style.setBorderRight(BorderStyle.THIN);
styleMap.put("header", style); return styleMap;
} public Workbook getWorkbook() {
return workbook;
} public void setWorkbook(Workbook workbook) {
this.workbook = workbook;
} public Sheet getSheet() {
return sheet;
} public void setSheet(Sheet sheet) {
this.sheet = sheet;
} public int getRowNum() {
return rowNum;
} public void setRowNum(int rowNum) {
this.rowNum = rowNum;
} public Map<String, CellStyle> getStyles() {
return styles;
} public void setStyles(Map<String, CellStyle> styles) {
this.styles = styles;
} public List<ColumnField> getColumns() {
return columns;
} public void setColumns(List<ColumnField> columns) {
this.columns = columns;
} @Override
public void close() throws IOException {
if (workbook instanceof SXSSFWorkbook && ((SXSSFWorkbook) workbook).dispose())
workbook.close();
} class ColumnField {
private String title;
private String param;
private Class<?> paramType;
private int width; ColumnField(String title, String param, Class<?> paramType, int width) {
this.title = title;
this.param = param;
this.paramType = paramType;
this.width = width;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public String getParam() {
return param;
} public void setParam(String param) {
this.param = param;
} public Class<?> getParamType() {
return paramType;
} public void setParamType(Class<?> paramType) {
this.paramType = paramType;
} public int getWidth() {
return width;
} public void setWidth(int width) {
this.width = width;
}
}
}

以下是两个注解

 @Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelField { /**
* 导出字段标题
*/
String title(); /**
* 列宽
*/
int width() default 10; // 后面还可以添加其他的属性,添加后再修改上面那个代码就行了
}

以上。

使用方式为:

 import com.xxx.utils.ExcelField;

 public class ExcelDataModel {

     @ExcelField(title = "ID", width = 4)
private String id; @ExcelField(title = "序号", width = 4)
private Integer serial; @ExcelField(title = "名字", width = 8)
private String name;
13 ... (getter\setter)
    @GetMapping(value = "export/post")
public void exportPost(@ModelAttribute RequestModel model, HttpServletResponse response) {
try (
ExcelExport excelExport = new ExcelExport();
OutputStream out = response.getOutputStream()
) {
List<ExcelDataModel> data = xxxService.selectExportData(model);
response.setContentType("octets/stream");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("xx列表", "UTF-8")
+ DateUtils.formatDate(new Date(), "yyyyMMddHHmmss") + ExcelExport.EXCEL_SUFFIX);
String title = "xx列表";
excelExport.createSheet("xx列表", title, ExcelDataModel.class);
excelExport.setDataList(data);
excelExport.write(out);
} catch (Exception e) {
e.printStackTrace();
}
}

over.

java 注解方式 写入数据到Excel文件中的更多相关文章

  1. java 写入数据到Excel文件中_Demo

    =======第一版:基本功能实现======= import com.google.common.collect.Maps; import org.apache.log4j.Logger; impo ...

  2. Java读取、写入、处理Excel文件中的数据(转载)

    原文链接 在日常工作中,我们常常会进行文件读写操作,除去我们最常用的纯文本文件读写,更多时候我们需要对Excel中的数据进行读取操作,本文将介绍Excel读写的常用方法,希望对大家学习Java读写Ex ...

  3. 写入数据到Plist文件中时,第一次要创建一个空的数组,否则写入文件失败

    #pragma mark - 保存数据到本地Plist文件中 - (void)saveValidateCountWithDate:(NSString *)date count:(NSString *) ...

  4. 效率最高的Excel数据导入---(c#调用SSIS Package将数据库数据导入到Excel文件中【附源代码下载】) 转

    效率最高的Excel数据导入---(c#调用SSIS Package将数据库数据导入到Excel文件中[附源代码下载])    本文目录: (一)背景 (二)数据库数据导入到Excel的方法比较   ...

  5. Python:将爬取的网页数据写入Excel文件中

    Python:将爬取的网页数据写入Excel文件中 通过网络爬虫爬取信息后,我们一般是将内容存入txt文件或者数据库中,也可以写入Excel文件中,这里介绍关于使用Excel文件保存爬取到的网页数据的 ...

  6. Python学习笔记_从CSV读取数据写入Excel文件中

    本示例特点: 1.读取CSV,写入Excel 2.读取CSV里具体行.具体列,具体行列的值 一.系统环境 1. OS:Win10 64位英文版 2. Python 3.7 3. 使用第三方库:csv. ...

  7. Java使用POI实现数据导出excel报表

    Java使用POI实现数据导出excel报表 在上篇文章中,我们简单介绍了java读取word,excel和pdf文档内容 ,但在实际开发中,我们用到最多的是把数据库中数据导出excel报表形式.不仅 ...

  8. java代码将excel文件中的内容列表转换成JS文件输出

    思路分析 我们想要把excel文件中的内容转为其他形式的文件输出,肯定需要分两步走: 1.把excel文件中的内容读出来: 2.将内容写到新的文件中. 举例 一张excel表中有一个表格: 我们需要将 ...

  9. 批量处理txt文本文件到Excel文件中去----java

    首发地址:http://blog.csdn.net/u014737138/article/details/38120403 不多说了 直接看代码: 下面的FileFind类首先是找到文件夹下面所有的t ...

随机推荐

  1. Maven 基础概念

    Project:任何你想构建的事务Maven都可以认为它们是工程,这些工程被定义为工程对象模型(project Object Model POM) 一个工程可以依赖其他的工程,一个工程也可以由多个子工 ...

  2. Oralce问题之ORA-12560:TNS协议适配器错误

    在Windows系统中,通过CMD命令打开命令窗口,通过命令:sqlplus / as sysdba回车后提示 协议适配器错误 可能原因: (1).Oralce数据库监听服务没启动起来 通过开始-&g ...

  3. SELinux 了解及CentOS7 中 semanage命令的安装

    SELinux 安全子系统 SELinux(Security-Enhanced Linux)是美国国家安全局在Linux开源社区的帮助下开发的一个强制访问控制(MAC,Mandatory Access ...

  4. Python 爬虫实现天气查询(可视化界面版)

    github项目地址:StarMan Python 实现天气查询的程序早已完成,近日开学无课,昨晚心血来潮想做一个较为友好的界面版本,便匆忙行动了起来. 在之前已有的程序的基础上使用Tkinter 模 ...

  5. 洛谷P1462 通往奥格瑞玛的道路(SPFA+二分答案)

    题目背景 在艾泽拉斯大陆上有一位名叫歪嘴哦的神奇术士,他是部落的中坚力量 有一天他醒来后发现自己居然到了联盟的主城暴风城 在被众多联盟的士兵攻击后,他决定逃回自己的家乡奥格瑞玛 题目描述 在艾泽拉斯, ...

  6. gdb 使用finish命令(缩写fin)

    gdb 使用finish命令(缩写fin) gdb 使用finish命令(缩写fin) gdb 使用finish命令(缩写fin) 跳出跟踪的函数

  7. mysql大数据解决方案--分表分库(0)

    引言 对于一个大型的互联网应用,海量数据的存储和访问成为了系统设计的瓶颈问题,对于系统的稳定性和扩展性造成了极大的问题.通过数据切分来提高网站性能,横向扩展数据层已经成为架构研发人员首选的方式. •水 ...

  8. Ubuntu打开系统监视器查看进程&资源等信息

    Ubuntu打开系统监视器查看进程&资源等信息 类似于Windows的任务管理器,Ubuntu也提供了系统监视器供用户管理进程及查看系统占用资源等 打开方式,终端输入如下命令: gnome-s ...

  9. jQuery.trim()方法

    定义和用法 $.trim() 函数用于去除字符串两端的空白字符. 注意:$.trim()函数会移除字符串开始和末尾处的所有换行符,空格(包括连续的空格)和制表符.如果这些空白字符在字符串中间时,它们将 ...

  10. VSCode 常用快捷键和常用插件及通用设置

    https://code.visualstudio.com/docs?start=true 一.常用快捷键:参考:https://blog.csdn.net/liwan09/article/detai ...