一、前台实现:
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 + " ").getBytes(Charsets.UTF_8)); for (String[] parts : lines) { final String line = Joiner.on(",").useForNull("").join(parts); outputStream.write((line + " ").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>
三、效果图如下: