生成csv格式文件并导出至页面的前后台实现

一、前台实现:


1. HTML:


<div>
  <a href="javascript:void(0);" class="btnStyleLeft">
    <span class="fa fa-external-link" οnclick="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;
    <br>  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>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值