一、前台实现:

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格式文件并导出至页面的前后台实现的更多相关文章

  1. java导出csv格式文件

    导出csv格式文件的本质是导出以逗号为分隔的文本数据 import java.io.BufferedWriter; import java.io.File; import java.io.FileIn ...

  2. 导出CSV格式文件,用Excel打开乱码的解决办法

    导出CSV格式文件,用Excel打开乱码的解决办法 1.治标不治本的办法 将导出CSV数据文件用记事本打开,然后另存为"ANSI"编码格式,再用Excel打开,乱码解决. 但是,这 ...

  3. 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 ...

  4. 如何将EDI报文转换为CSV格式文件?

    如果您对EDI项目实施有一定的了解,想必您一定知道,在正式开始EDI项目实施之前,都会有EDI顾问与您接洽,沟通EDI项目需求.其中,会包含EDI通信双方使用哪种传输协议,传输的报文是符合什么标准的, ...

  5. Python数据写入csv格式文件

    (只是传递,基础知识也是根基) Python读取数据,并存入Excel打开的CSV格式文件内! 这里需要用到bs4,csv,codecs,os模块. 废话不多说,直接写代码!该重要的内容都已经注释了, ...

  6. 生成Csv格式的字符串

    using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Sy ...

  7. weka数据挖掘拾遗(一)---- 生成Arff格式文件

    一.什么是arff格式文件 1.arff是Attribute-Relation File Format缩写,从英文字面也能大概看出什么意思.它是weka数据挖掘开源程序使用的一种文件模式.由于weka ...

  8. python3 库pandas写入csv格式文件出现中文乱码问题解决方法

    python3 库pandas写入csv格式文件出现中文乱码问题解决方法 解决方案: 问题是使用pandas的DataFrame的to_csv方法实现csv文件输出,但是遇到中文乱码问题,已验证的正确 ...

  9. 使用Spark读写CSV格式文件(转)

    原文链接:使用Spark读写CSV格式文件 CSV格式的文件也称为逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号.在本文中的CSV格 ...

随机推荐

  1. 解决指向iframe的target失效

    今天遇到一个bug. 主页面中点击左侧导航栏[某]项后,右侧的iframe页面加载到了新窗口.之后,所有选项的iframe加载都异常. 检查<a>标签target="main&q ...

  2. 在.Net中将RocketMQ跑起来_入门篇【2】

    上一篇讲了如何再控制台将RocketMQ跑起来,本篇讲解,在asp.net mvc种跑起来,含(发布.订阅). 本次将不挨个贴源码,直接展示目录,根据上一篇文章,进行相应的调整即可. 1.新建一个类库 ...

  3. Hbuilder实用技巧

    转自:http://blog.csdn.net/qq_34099161/article/details/51451712 1. Q:怎么实现代码追踪? A:在编辑代码时经常会出现需要跳转到引用文件或者 ...

  4. Lua语言的介绍和编程语言的归类

    Lua 本条目介绍的是一种编程语言.关于关于Lua在维基百科中的使用,请见"维基百科:Lua".关于"Lua"一词的其他意思,请见"卢阿". ...

  5. Vue.js 1.x 和 2.x 实例的生命周期

    在Vue.js中,在实例化Vue之前,它们都是以HTML的文本形式存在文本编辑器中.当实例化后将经历创建.编译.销毁三个主要阶段. 以下是Vue.js 1.x  实例的生命周期图示: Vue.js 1 ...

  6. linux服务器,svn认证失败,配置问题,防火墙等等

    之前自己还真没设置过SVN,今天亲自动手,错误百出,真是够头疼的.在网上随便找了一篇文章,就按照文章介绍开始安装.怎么安装和设置我就不说了,这里主要记录遇到的问题. 1.不知道该怎么设置 svn:// ...

  7. [SinGuLaRiTy] 复习模板-数学

    [SinGuLaRiTy-1047] Copyright (c) SinGuLaRiTy 2017. All Rights Reserved. 质因数分解 void solve(int n) { == ...

  8. P2P视频模块

    P2P视频模块数据手册 公  司 : 深圳市万秀电子有限公司 网  站 : http://www.wanxiucx.com 总  机 : 0755-23215689 联系人: 张先生 手  机 : 1 ...

  9. Node.js进阶:5分钟入门非对称加密方法

    前言 刚回答了SegmentFault上一个兄弟提的问题<非对称解密出错>.这个属于Node.js在安全上的应用,遇到同样问题的人应该不少,基于回答的问题,这里简单总结下. 非对称加密的理 ...

  10. Java 得到泛型中得到T.class

    Class <T> entityClass = (Class <T>) ((ParameterizedType) getClass().getGenericSuperclass ...