生成csv格式文件并导出至页面的前后台实现
一、前台实现:
1. HTML:
<div>
<a href="javascript:void(0);" class="btnStyleLeft">
<span class="fa fa-external-link" onclick="test.exportGridData()">导出</span>
</a>
</div>
2.js:
/*导出查询记录到本地下载目录*/
exportGridData: function(type) {
var exportIFrame = document.createElement("iframe");
exportIFrame.src = "/ipeg-web/requestDispatcher?" + exportParams.join("&"); // exportParams带入需要传至后台的参数
exportIFrame.style.display = "none";
document.body.appendChild(exportIFrame);
},
二、后台实现:
1、ExtensionMode枚举---用于csv/txt/excel2003/excel2007文件的写入
import com.csvreader.CsvWriter;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List; public enum ExtensionMode {
TXT(".txt", "application/octet-stream") {
@Override
public void write(List<String[]> lines, String[] header, OutputStream outputStream) throws IOException {
checkNotNull(lines, header, outputStream);
final String headerString = Joiner.on(",").useForNull("").join(header);
outputStream.write((headerString + "\r\n").getBytes(Charsets.UTF_8));
for (String[] parts : lines) {
final String line = Joiner.on(",").useForNull("").join(parts);
outputStream.write((line + "\r\n").getBytes(Charsets.UTF_8));
}
}
},
CSV(".csv", "application/octet-stream") {
@Override
public void write(List<String[]> lines, String[] header, OutputStream outputStream) throws IOException {
checkNotNull(lines, header, outputStream);
final CsvWriter csvWriter = new CsvWriter(outputStream, ',', Charsets.UTF_8);
try {
csvWriter.writeRecord(header);
for (String[] parts : lines) {
csvWriter.writeRecord(parts);
}
csvWriter.flush();
} finally {
csvWriter.close();
}
}
},
EXCEL2003(".xls", "application/vnd.ms-excel") {
@Override
public void write(List<String[]> lines, String[] header, OutputStream outputStream) throws IOException {
checkNotNull(lines, header, outputStream);
final Workbook workbook = new ExcelMaker() {
@Override
protected Workbook createWorkbook() {
return new HSSFWorkbook();
}
}.make(lines, header);
workbook.write(outputStream);
}
},
EXCEL2007(".xlsx", "application/vnd.ms-excel") {
@Override
public void write(List<String[]> lines, String[] header, OutputStream outputStream) throws IOException {
checkNotNull(lines, header, outputStream);
final Workbook workbook = new ExcelMaker() {
@Override
protected Workbook createWorkbook() {
return new XSSFWorkbook();
}
}.make(lines, header);
workbook.write(outputStream);
}
};
private static void checkNotNull(List<String[]> lines, String[] header, OutputStream outputStream) {
Preconditions.checkNotNull(lines, "null list for write");
Preconditions.checkNotNull(header, "null header");
Preconditions.checkNotNull(outputStream, "null output stream ");
}
private final String suffix;
private final String contentType; ExtensionMode(String suffix, String contentType) {
this.suffix = suffix;
this.contentType = contentType;
} public String getSuffix() {
return suffix;
} public String getContentType() {
return contentType;
} public static ExtensionMode getExtensionModeBySuffix(String suffix) {
for (ExtensionMode mode : ExtensionMode.values()) {
if (mode.getSuffix().equalsIgnoreCase(suffix))
return mode;
}
throw new IllegalArgumentException("Unknown File Type.");
} public abstract void write(List<String[]> lines, String[] header, OutputStream outputStream)
throws IOException; private abstract static class ExcelMaker {
public Workbook make(List<String[]> lines, String[] header) {
Workbook wb = createWorkbook();
Sheet sheet = wb.createSheet("数据源");
// 创建格式
CellStyle cellStyle = getCellStyle(wb);
// 添加第一行标题
addHeader(header, sheet, cellStyle);
// 从第二行开始写入数据
addData(lines, sheet, cellStyle);
return wb;
} private void addData(List<String[]> lines, Sheet sheet, CellStyle cellStyle) {
for (int sn = 0; sn < lines.size(); sn++) {
String[] col = lines.get(sn);
Row row = sheet.createRow(sn + 1);
for (int cols = 0; cols < col.length; cols++) {
Cell cell = row.createCell(cols);
cell.setCellStyle(cellStyle);
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
cell.setCellValue(col[cols]);
}
}
} private CellStyle getCellStyle(Workbook wb) {
Font font = wb.createFont();
font.setColor(HSSFFont.COLOR_NORMAL);
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setFont(font);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return cellStyle;
} private void addHeader(String[] header, Sheet sheet, CellStyle cellStyle) {
Row titleRow = sheet.createRow(0);
// 创建第1行标题单元格
for (int i = 0, size = header.length; i < size; i++) {
switch (i) {
case 5:
case 7:
sheet.setColumnWidth(i, 10000);
break;
default:
sheet.setColumnWidth(i, 3500);
break;
}
Cell cell = titleRow.createCell(i, 0);
cell.setCellStyle(cellStyle);
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
cell.setCellValue(header[i]);
}
}
protected abstract Workbook createWorkbook();
}
}
2. dataExport:具体的数据导出
public class dataExport {
private final byte[] UTF_BOM = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
private final String[] header = new String[]{"user", "name", "id"};
List logData = null;
OutputStream outputStream = null;
outputStream = response.getOutputStream();
try {
export(ExtensionMode.CSV, header, getUserData(logData), outputStream);
} catch (IOException e) {
e.printStackTrace();
}finally{
if (outputStream != null)
{
try
{
outputStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
private void export(ExtensionMode extensionMode, String[] header, ImmutableList<String[]> lines,
OutputStream outputStream) throws IOException {
response.setContentType(extensionMode.getContentType() + ";charset=UTF-8");
response.reset();
response.setHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(getFileName(extensionMode.getSuffix()), "UTF-8"));
if (extensionMode == ExtensionMode.CSV) {
outputStream.write(UTF_BOM); //防止中文乱码
}
extensionMode.write(lines, header, outputStream);
outputStream.flush();
}
private String getFileName(String extension) {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
return format.format(new Date()) + extension;
}
public ImmutableList<String[]> getUserData(List<UserEntity> data) {
return from(data).transform(new userDataFunction()).toList();
}
private class userDataFunction implements Function<UserEntity, String[]> {
@Override
public String[] apply(UserEntity input) {
return new String[]{
input.getName(),
input.getUser(),
input.getId()
};
}
}
}
3.需要添加的maven依赖如下:
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi-ooxml</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.7</version>
</dependency>
三、效果图如下:

生成csv格式文件并导出至页面的前后台实现的更多相关文章
- java导出csv格式文件
导出csv格式文件的本质是导出以逗号为分隔的文本数据 import java.io.BufferedWriter; import java.io.File; import java.io.FileIn ...
- 导出CSV格式文件,用Excel打开乱码的解决办法
导出CSV格式文件,用Excel打开乱码的解决办法 1.治标不治本的办法 将导出CSV数据文件用记事本打开,然后另存为"ANSI"编码格式,再用Excel打开,乱码解决. 但是,这 ...
- MYSQL导入CSV格式文件数据执行提示错误(ERROR 1290): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement.
MYSQL导入CSV格式文件数据执行提示错误(ERROR 1290): The MySQL server is running with the --secure-file-priv option s ...
- 如何将EDI报文转换为CSV格式文件?
如果您对EDI项目实施有一定的了解,想必您一定知道,在正式开始EDI项目实施之前,都会有EDI顾问与您接洽,沟通EDI项目需求.其中,会包含EDI通信双方使用哪种传输协议,传输的报文是符合什么标准的, ...
- Python数据写入csv格式文件
(只是传递,基础知识也是根基) Python读取数据,并存入Excel打开的CSV格式文件内! 这里需要用到bs4,csv,codecs,os模块. 废话不多说,直接写代码!该重要的内容都已经注释了, ...
- 生成Csv格式的字符串
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Sy ...
- weka数据挖掘拾遗(一)---- 生成Arff格式文件
一.什么是arff格式文件 1.arff是Attribute-Relation File Format缩写,从英文字面也能大概看出什么意思.它是weka数据挖掘开源程序使用的一种文件模式.由于weka ...
- python3 库pandas写入csv格式文件出现中文乱码问题解决方法
python3 库pandas写入csv格式文件出现中文乱码问题解决方法 解决方案: 问题是使用pandas的DataFrame的to_csv方法实现csv文件输出,但是遇到中文乱码问题,已验证的正确 ...
- 使用Spark读写CSV格式文件(转)
原文链接:使用Spark读写CSV格式文件 CSV格式的文件也称为逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号.在本文中的CSV格 ...
随机推荐
- 线性表的顺序存储结构的实现及其应用(C/C++实现)
存档--- #include <stdio.h> #include <stdlib.h> typedef int ElemType; #define MAXSIZE 10 #i ...
- poj_1144Network(tarjan求割点)
poj_1144Network(tarjan求割点) 标签: tarjan 割点割边模板 题目链接 Network Time Limit: 1000MS Memory Limit: 10000K To ...
- docker创建ceph集群
背景 Ceph官方现在提供两类镜像来创建集群,一种是常规的,每一种Ceph组件是单独的一个镜像,如ceph/daemon.ceph/radosgw.ceph/mon.ceph/osd等:另外一种是最新 ...
- cesium编程入门(二)环境搭建
环境搭建 环境搭建 编译 node 安装 Node.js安装包及源码下载地址为:https://nodejs.org/en/download/. 安装完成后,打开命令行,输入:node -v,如果结果 ...
- Spark性能调优之资源分配
Spark性能调优之资源分配 性能优化王道就是给更多资源!机器更多了,CPU更多了,内存更多了,性能和速度上的提升,是显而易见的.基本上,在一定范围之内,增加资源与性能的提升,是成正比的:写完了 ...
- js数组操作记录
一 .splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目. arrayObject.splice(index,howmany,item1,.....,itemX) 参数 描述 in ...
- Robots.txt - 禁止爬虫
robots.txt用于禁止网络爬虫访问网站指定目录.robots.txt的格式采用面向行的语法:空行.注释行(以#打头).规则行.规则行的格式为:Field: value.常见的规则行:User-A ...
- iis配置完成,出现HTTP 错误 403.14 - Forbidden
版权声明:本文为博主原创文章,未经博主允许不得转载.转载请标明文章出处和原文链接. 403.14 禁止访问:在 Web 服务器上已拒绝目录列表 解决方案一:一般情况站点都是不会允许直接读取目录内容的, ...
- dedecms v5.7 图片集“图集内容”无法调用的解决办法
在dedecms的图片集模型或者基于图片集模型修改的自定义模型中 内容页模板使用 {dede:field.body/} 方式来调用body字段是没有输出的(原因不明,未继续深入) 但有些时候当需要在内 ...
- 月薪20k以上的高级程序员需要学习哪些技术呢?
课程内容: 源码分析.分布式架构.微服务架构.性能优化.团队协作效率.双十一项目实战 适用对象: 1-5年或更长软件开发经验,没有工作经验但基础非常扎实,对java工作机制,常用设计思想,常用java ...