import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*; public class WriterExcelUtil { private static final Logger LOGGER = LoggerFactory.getLogger(WriterExcelUtil.class.getName()); public static void main(String[] args) {
String path = "E://demo.xlsx";
String name = "test";
List<String> titles =Lists.newArrayList();
titles.add("id");
titles.add("name");
titles.add("age");
titles.add("birthday");
titles.add("gender");
titles.add("date");
List<Map<String, Object>> values = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
Map<String, Object> map = Maps.newHashMap();
map.put("id", i + 1D);
map.put("name", "test_" + i);
map.put("age", i * 1.5);
map.put("gender", "man");
map.put("birthday", new Date());
map.put("date", Calendar.getInstance());
values.add(map);
}
System.out.println(writerExcel(path, name, titles, values));
} /**
* 数据写入Excel文件
*
* @param path 文件路径,包含文件全名,例如:D://file//demo.xls
* @param name sheet名称
* @param titles 行标题列
* @param values 数据集合,key为标题,value为数据
* @return True\False
*/
public static boolean writerExcel(String path, String name, List<String> titles, List<Map<String, Object>> values) {
LOGGER.info("path : {}", path);
String style = path.substring(path.lastIndexOf("."), path.length()).toUpperCase(); // 从文件路径中获取文件的类型
return generateWorkbook(path, name, style, titles, values);
} /**
* 将数据写入指定path下的Excel文件中
*
* @param path 文件存储路径
* @param name sheet名
* @param style Excel类型
* @param titles 标题串
* @param values 内容集
* @return True\False
*/
private static boolean generateWorkbook(String path, String name, String style, List<String> titles, List<Map<String, Object>> values) {
LOGGER.info("file style : {}", style);
Workbook workbook;
if ("XLS".equals(style.toUpperCase())) {
workbook = new HSSFWorkbook();
} else {
workbook = new XSSFWorkbook();
}
// 生成一个表格
Sheet sheet;
if (null == name || "".equals(name)) {
sheet = workbook.createSheet(); // name 为空则使用默认值
} else {
sheet = workbook.createSheet(name);
}
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 15);
// 生成样式
Map<String, CellStyle> styles = createStyles(workbook);
/*
* 创建标题行
*/
Row row = sheet.createRow(0);
// 存储标题在Excel文件中的序号
Map<String, Integer> titleOrder = Maps.newHashMap();
for (int i = 0; i < titles.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(styles.get("header"));
String title = titles.get(i);
cell.setCellValue(title);
titleOrder.put(title, i);
}
/*
* 写入正文
*/
Iterator<Map<String, Object>> iterator = values.iterator();
int index = 0; // 行号
while (iterator.hasNext()) {
index++; // 出去标题行,从第一行开始写
row = sheet.createRow(index);
Map<String, Object> value = iterator.next();
for (Map.Entry<String, Object> map : value.entrySet()) {
// 获取列名
String title = map.getKey();
// 根据列名获取序号
int i = titleOrder.get(title);
// 在指定序号处创建cell
Cell cell = row.createCell(i);
// 设置cell的样式
if (index % 2 == 1) {
cell.setCellStyle(styles.get("cellA"));
} else {
cell.setCellStyle(styles.get("cellB"));
}
// 获取列的值
Object object = map.getValue();
// 判断object的类型
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (object instanceof Double) {
cell.setCellValue((Double) object);
} else if (object instanceof Date) {
String time = simpleDateFormat.format((Date) object);
cell.setCellValue(time);
} else if (object instanceof Calendar) {
Calendar calendar = (Calendar) object;
String time = simpleDateFormat.format(calendar.getTime());
cell.setCellValue(time);
} else if (object instanceof Boolean) {
cell.setCellValue((Boolean) object);
} else {
cell.setCellValue(object.toString());
}
}
}
/*
* 写入到文件中
*/
boolean isCorrect = false;
try {
File file = new File(path);
OutputStream outputStream = new FileOutputStream(file);
workbook.write(outputStream);
outputStream.close();
isCorrect = true;
} catch (IOException e) {
isCorrect = false;
LOGGER.error("write Excel file error : {}", e.getMessage());
}
try {
workbook.close();
} catch (IOException e) {
isCorrect = false;
LOGGER.error("workbook closed error : {}", e.getMessage());
}
return isCorrect;
} /**
* Create a library of cell styles
*/
/**
* @param wb
* @return
*/
private static Map<String, CellStyle> createStyles(Workbook wb) {
Map<String, CellStyle> styles = Maps.newHashMap(); // 标题样式
CellStyle titleStyle = wb.createCellStyle();
titleStyle.setAlignment(HorizontalAlignment.CENTER); // 水平对齐
titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直对齐
titleStyle.setLocked(true); // 样式锁定
titleStyle.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
Font titleFont = wb.createFont();
titleFont.setFontHeightInPoints((short) 16);
titleFont.setBold(true);
titleFont.setFontName("微软雅黑");
titleStyle.setFont(titleFont);
styles.put("title", titleStyle); // 文件头样式
CellStyle headerStyle = wb.createCellStyle();
headerStyle.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex()); // 前景色
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 颜色填充方式
headerStyle.setWrapText(true);
headerStyle.setBorderRight(BorderStyle.THIN); // 设置边界
headerStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
headerStyle.setBorderLeft(BorderStyle.THIN);
headerStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
headerStyle.setBorderTop(BorderStyle.THIN);
headerStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
headerStyle.setBorderBottom(BorderStyle.THIN);
headerStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
Font headerFont = wb.createFont();
headerFont.setFontHeightInPoints((short) 12);
headerFont.setColor(IndexedColors.WHITE.getIndex());
titleFont.setFontName("微软雅黑");
headerStyle.setFont(headerFont);
styles.put("header", headerStyle); Font cellStyleFont = wb.createFont();
cellStyleFont.setFontHeightInPoints((short) 12);
cellStyleFont.setColor(IndexedColors.BLUE_GREY.getIndex());
cellStyleFont.setFontName("微软雅黑"); // 正文样式A
CellStyle cellStyleA = wb.createCellStyle();
cellStyleA.setAlignment(HorizontalAlignment.CENTER); // 居中设置
cellStyleA.setVerticalAlignment(VerticalAlignment.CENTER);
cellStyleA.setWrapText(true);
cellStyleA.setBorderRight(BorderStyle.THIN);
cellStyleA.setRightBorderColor(IndexedColors.BLACK.getIndex());
cellStyleA.setBorderLeft(BorderStyle.THIN);
cellStyleA.setLeftBorderColor(IndexedColors.BLACK.getIndex());
cellStyleA.setBorderTop(BorderStyle.THIN);
cellStyleA.setTopBorderColor(IndexedColors.BLACK.getIndex());
cellStyleA.setBorderBottom(BorderStyle.THIN);
cellStyleA.setBottomBorderColor(IndexedColors.BLACK.getIndex());
cellStyleA.setFont(cellStyleFont);
styles.put("cellA", cellStyleA); // 正文样式B:添加前景色为浅黄色
CellStyle cellStyleB = wb.createCellStyle();
cellStyleB.setAlignment(HorizontalAlignment.CENTER);
cellStyleB.setVerticalAlignment(VerticalAlignment.CENTER);
cellStyleB.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
cellStyleB.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyleB.setWrapText(true);
cellStyleB.setBorderRight(BorderStyle.THIN);
cellStyleB.setRightBorderColor(IndexedColors.BLACK.getIndex());
cellStyleB.setBorderLeft(BorderStyle.THIN);
cellStyleB.setLeftBorderColor(IndexedColors.BLACK.getIndex());
cellStyleB.setBorderTop(BorderStyle.THIN);
cellStyleB.setTopBorderColor(IndexedColors.BLACK.getIndex());
cellStyleB.setBorderBottom(BorderStyle.THIN);
cellStyleB.setBottomBorderColor(IndexedColors.BLACK.getIndex());
cellStyleB.setFont(cellStyleFont);
styles.put("cellB", cellStyleB); return styles;
}
}

数据导出 写入到excle文件的更多相关文章

  1. 将页面中表格数据导出excel格式的文件(vue)

    近期由于项目需要,需要将页面中的表格数据导出excel格式的文件,折腾了许久,在网上各种百度,虽然资料不少,但是大都不全,踩了许多坑,总算是皇天不负有心人,最后圆满解决了. 1.安装相关依赖(npm安 ...

  2. SQL Server将数据导出到SQL脚本文件

    http://www.studyofnet.com/news/list-8883.2-1-4.html 一.SQL Server 2008将数据导出到SQL脚本文件 1.打开SQL Server200 ...

  3. MongoDB中的数据导出为excel CSV 文件

    1.打开命令行,进入我们所安装的mongodb路径下的bin文件夹 2.我们采用bin文件夹下的mongoexport方法进行导出, mongoexport -d myDB -c user -f _i ...

  4. c# .Net :Excel NPOI导入导出操作教程之数据库表信息数据导出到一个Excel文件并写到磁盘示例分享

      string sql = @"select * from T_Excel"; ----------------DataTable Star----------------    ...

  5. Python3 Pandas的DataFrame格式数据写入excle文件、json、html、剪贴板、数据库

    Python3 Pandas的DataFrame格式数据写入excle文件.json.html.剪贴板.数据库 一.DataFrame格式数据 Pandas是Python下一个开源数据分析的库,它提供 ...

  6. 使用Sql Server Management Studio 2008将数据导出到Sql文件中

      最近需要将一个Sql Server 2005数据库中的数据导出,为了方便,就希望能导出成Sql文件,里面包含的数据是由Insert 语句组成的. 在Sql Server Management St ...

  7. python学习笔记3.2_数据导出

    一.data.to_csv:数据导出 1.to_csv:将数据导出为逗号分隔的文件 2.输出为其他分隔符的文件 写入到控制台,并打印:sys.stdout na_rep:对空值进行标注 二.serie ...

  8. SpringMVC 实现POI读取Excle文件中数据导入数据库(上传)、导出数据库中数据到Excle文件中(下载)

    读取Excale表返回一个集合: package com.shiliu.game.utils; import java.io.File; import java.io.FileInputStream; ...

  9. 数据导出至excle

    ASP.NET MVC导出Excel 首先下载  NPOI.dll 引用到项目中 建议下载地址:http://download.csdn.net/detail/pukuimin1226/5851747 ...

随机推荐

  1. Oracle Grid,ASM,Database on Redhat 7.5

    目录 Oracle安装包 Oracle官方文档 Blog Oracle Grid Installation Process 用户.组.目录 Oracleasm 创建 ASM 磁盘 Database S ...

  2. readlink 查看符号链接的文件的内容

    1. 命令功能 readlink 查看软链接文件里的真实内容. 2. 语法格式 readlink [option]  file 参数 参数说明 -f 后跟软链接文件 3. 使用范例 范例1 查看文件链 ...

  3. 查找目录下指定类型的所有文件(maven 打包提取脚本)

    1 首先想到的是递归遍历目录 筛选出符合条件的文件 dir命令递归遍历目录 /b控制显示格式 /s递归  /ad 只显示目录 dir /b/s .\* 判断文件类型 操作数得用`` rem 取出文件扩 ...

  4. less:匹配模式

    相当于JS中的if(不完全是),满足条件后才能匹配 .margin(top, @width: 5px) { margin: @width 0 0 0; } .margin(right, @width: ...

  5. Vue 组件间的传值(通讯)

    组件之间的通讯分为三种 父给子传 子给父传 兄弟组件之间的通讯 1 父组件给子组件传值 子组件嵌套在父组件内部,父组件给子组件传递一个标识,在子组件内部用props接收,子组件在模板里可以通过{{}} ...

  6. python tkinter画圆

    x0=150    #圆心横坐标 y0=100    #圆心纵坐标 canvas.create_oval(x0-10,y0-10,x0+10,y0+10)    #圆外矩形左上角与右下角坐标 canv ...

  7. 三星GT S7562 PIN 解锁方法

    三星GT S7562  PIN 解锁方法 请认真阅读完下文再进行操作,操作基本安全,请保证你手机电池有电续航超过1小时 首先把内存开和电话卡取出(以防万一数据丢失) 关机状态下: 同时按音量上下键 加 ...

  8. 英语单词independent

    来源——https://www.docker.com/products/docker-hub 回到顶部 Share and Collaborate with Docker Hub Docker Hub ...

  9. 日志管理工具logrotate

    工作所需,需要管理脚本的打印日志,百度一圈,发现了logrotate这款工具,经测试确实挺好的! 话不多说,直接上重点,以便于以后需要时查看 命令: whereis logrotate 可以看到log ...

  10. iOS---实现简书和知乎的上滑隐藏导航栏下拉显示导航栏效果

    因为自己用简书和知乎比较多,所以对其导航栏的效果比较好奇,自己私下里找资料实现了一下.这个效果的关键点在于下方可供滑动的内容的便宜距离inset的改变,以及滑动的scrollview代理的执行,废话不 ...