博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java+vue实现excel文件从服务器下载
阅读量:2441 次
发布时间:2019-05-10

本文共 7564 字,大约阅读时间需要 25 分钟。

excel处理全套流程

前端代码

选取文件
上传到服务器
上传文件请命名为tid.xlsx或者utid.xlsx,excel文件第一列为要转换的数据

on-success表示文件上传处理成功之后调用的下载函数

submitUpload为点击上传的函数

submitUpload () {
if (this.type == null) {
this.$alert('请选择转换类型', '警告') return } this.$refs.upload.submit() }, handleAvatarSuccess () {
axios({
url: 'http://127.0.0.1:8080/help/download', method: 'post', //下面这句必须有,表示返回的是文件 responseType: 'blob', headers: {
'X-Requested-With': 'XMLHttpRequest' }, params: {
type: this.type } }).then(res => {
//获取文件名,需要在后端进行配置 let filename = res.headers['filename'] let type = res.headers['content-type'].split(';')[0] let blob = new Blob([res.data], {
type: type }) const a = document.createElement('a') // 创建URL const blobUrl = window.URL.createObjectURL(blob) a.download = filename a.href = blobUrl document.body.appendChild(a) // 下载文件 a.click() // 释放内存 URL.revokeObjectURL(blobUrl) document.body.removeChild(a) }) }

后端代码

//文件下载    @PostMapping(value = "/download")    @ResponseBody    public void downloadFiles(@RequestParam(value = "type", required = true) String type,                              HttpServletResponse response) {
if (StringUtils.isBlank(type)) {
//return error(CommonErrorCode.COM_INVALID_PARAMETER, "文档id有误"); System.out.println("请先输入要处理的文档"); } try {
String fileName; if (type.equals("tidToUtid")) {
fileName = "tidToUtid.xlsx"; } else {
fileName = "utidToTid.xlsx"; } //服务器对应的文件的路径 String file = "/Users/dxm/Desktop/" + fileName; // 得到这个excel表格对象 XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(file)); OutputStream fos = null; fos = response.getOutputStream(); response.setCharacterEncoding("UTF-8"); // 设置contentType为excel格式 response.setContentType("application/vnd.ms-excel;charset=utf-8"); //下面这三行必须设置前端才可以读取到文件名 response.setHeader("Content-Disposition", fileName); response.setHeader("filename", fileName); response.setHeader("Access-Control-Expose-Headers", "filename"); wb.write(fos); fos.close(); } catch (FileNotFoundException e) {
logger.error("下载文档异常-找不到文件:{}", e); //return error(CommonErrorCode.COM_UNKNOWN_ERROR, "找不到文件"); } catch (UnsupportedEncodingException e) {
logger.error("下载文档异常-编码转换:{}", e); //return error(CommonErrorCode.COM_UNKNOWN_ERROR, "编码转换失败"); } catch (IOException e) {
logger.error("下载文档异常-io:{}", e); //return error(CommonErrorCode.COM_UNKNOWN_ERROR, "下载文档异常"); } }

java生成excel文件

public class ExcelExporter {
private static final Logger LOGGER = LoggerFactory.getLogger(ExcelExporter.class); private static final String[] tableNameTU = {
"***", "***", "***"}; private static final String[] tableNameUT = {
"***", "***", "***"}; private String[] headerNames; private Workbook workBook = new XSSFWorkbook(); private Sheet sheet; /** * @param tableName 表头 */ public ExcelExporter(String tableName) {
if (tableName.equals("tidToUtid")) {
this.headerNames = tableNameTU; } else {
this.headerNames = tableNameUT; } sheet = workBook.createSheet("sheet1"); initHeader(); } /** * 初始化表头信息 */ private void initHeader() {
// 创建第一行 Row row = sheet.createRow(0); Cell cell = null; // 创建表头 for (int i = 0; i < headerNames.length; i++) {
cell = row.createCell(i); cell.setCellValue(headerNames[i]); setCellStyle(cell); } } /** * 设置单元格样式 * * @param cell 单元格 */ public void setCellStyle(Cell cell) {
// 设置样式 CellStyle cellStyle = workBook.createCellStyle(); // 设置字体 Font font = workBook.createFont(); font.setFontName("宋体"); font.setFontHeightInPoints((short) 13); cellStyle.setFont(font); cell.setCellStyle(cellStyle); } public void createTableRows(List
data) {
int size = data.size(); for (int i = 0; i < size; i++) {
String[] flag = data.get(i).split(","); Row row = sheet.createRow(i + 1); Cell cell; int tableLength = 3; for (int j = 0; j < tableLength; j++) {
String value = flag[j]; cell = row.createCell(j); cell.setCellType(CellType.STRING); cell.setCellValue(value); } } } /** * 根据表头自动调整列宽度 */ public void autoAllSizeColumn() {
if (sheet instanceof SXSSFSheet) {
// 如果是SXSSFSheet,需要调用trackAllColumnsForAutoSizing方法一次 SXSSFSheet tmpSheet = (SXSSFSheet) sheet; tmpSheet.trackAllColumnsForAutoSizing(); } for (int i = 0, length = headerNames.length; i < length; i++) {
sheet.autoSizeColumn(i); } } /** * 将数据写出到excel中 * * @param outputStream */ public void exportExcel(OutputStream outputStream) {
// 导出之前先自动设置列宽 this.autoAllSizeColumn(); try {
workBook.write(outputStream); } catch (IOException e) {
LOGGER.error(" exportExcel error", e); } finally {
IOUtils.closeQuietly(outputStream); } } /** * 将数据写出到excel中 * * @param outputFilePath */ public void exportExcel(String outputFilePath) {
// 导出之前先自动设置列宽 this.autoAllSizeColumn(); FileOutputStream outputStream = null; try {
outputStream = new FileOutputStream(outputFilePath); workBook.write(outputStream); } catch (IOException e) {
LOGGER.error(" exportExcel error", e); } finally {
IOUtils.closeQuietly(outputStream); } }}

java读取excel文件

public class ExcelUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUtils.class); public static List
excelToShopIdList(InputStream inputStream) {
List
list = new ArrayList<>(); Workbook workbook; try {
workbook = WorkbookFactory.create(inputStream); inputStream.close(); //工作表对象 Sheet sheet = workbook.getSheetAt(0); //总行数 int rowLength = sheet.getLastRowNum() + 1; //工作表的列 Row row = sheet.getRow(0); //总列数 //int colLength = row.getLastCellNum(); //得到指定的单元格 Cell cell; for (int i = 0; i < rowLength; i++) {
row = sheet.getRow(i); cell = row.getCell(0); if (cell != null) {
String data = cell.getStringCellValue(); data = data.trim(); if (!data.equals("")) {
list.add(data); } } } } catch (Exception e) {
LOGGER.error("parse excel file error :", e); } return list; }}

转载地址:http://jwjqb.baihongyu.com/

你可能感兴趣的文章
智能Web算法第二版前言和译者序
查看>>
看HashMap源码前的必备冷知识,白话文式教学,适合刚开始了解源码的新手观看
查看>>
Spring-data-redis在shiro中的实例
查看>>
WinXP优化 全面消除操作系统的复制乱码(转)
查看>>
限制只能中文输入的方法(转)
查看>>
一张图搞定Java面向对象
查看>>
Borland ALM之需求定义和管理解决方案
查看>>
Verizon选择Borland控制开发流程并降低风险
查看>>
Borland 崭新的Caliber Define IT产品
查看>>
IBM Rational RequisitePro集成简介
查看>>
一年的测试生活和感悟
查看>>
持续改进之配置管理变更的关键路径
查看>>
mongodb replica sets 测试
查看>>
linux AS6.2 与 as5.4 的对比,性能提升明显
查看>>
FLASHCACHE 的是是非非
查看>>
99-lisp lisp 的99个问题 P1-10
查看>>
PG 函数的易变性(Function Volatility Categories)
查看>>
Lisp Quote 和Backquote分析
查看>>
PG psql 变彩色显示
查看>>
SICP 练习 1.3
查看>>