EXCEL 表格

一、依赖
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.0.1</version>
</dependency>
二、导入
HTML结构,用表单接收上传的文件
<form id='import' enctype='multipart/form-data' style='text-align: center'>
    <input type='file' name='file' style='margin: 30px auto'> -> 选择提交的文件
</form>
JavaScript脚本,封装上传到服务器的文件
var $file = $("input[name=file]");
var name = $file.val();
var suffix = name.substring(name.lastIndexOf('.'));
if (suffix == '.xls' || suffix == '.xlsx') {
    var data = new FormData();
    data.append("file", $file[0].files[0]);
    $.ajax({
            type: "POST",
            data: data,
            contentType: false,
            processData: false,
            mimeType: "multipart/form-data",
            url: "/import",
            success: function () {},
    });
} else {
    console.log("不是EXCEL文件");
}
服务器端接收前端传过来的文件
@PostMapping("/import")
@ResponseBody
public boolean important(MultipartFile file) throws Exception {
    String name = file.getOriginalFilename();
    String suffix = name.substring(name.lastIndexOf("."));
    if (suffix.equalsIgnoreCase(".xls")) { -> 2003版本
        POIFSFileSystem system = new POIFSFileSystem(file.getInputStream());
        HSSFWorkbook workbook = new HSSFWorkbook(system);
        HSSFSheet sheet = workbook.getSheetAt(0);
        int rows = sheet.getLastRowNum();
        for (int i = 1; i <= rows; i++) {
            HSSFRow row = sheet.getRow(i);
            int columns = row.getLastCellNum();
            for (int j = 0; j < columns; j++) {
                HSSFCell cell = row.getCell(j);
                if (row.getCell(j) == null) row.createCell(j);
                cell.setCellType(CellType.STRING);
                String content = cell.getStringCellValue();
                System.out.println(i + " " + j + " " + content);
            }
        }
    } else if (suffix.equalsIgnoreCase(".xlsx")) { -> 2007版本
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        XSSFSheet sheet = workbook.getSheetAt(0);
        int rows = sheet.getLastRowNum();
        for (int i = 1; i <= rows; i++) {
            XSSFRow row = sheet.getRow(i);
            int columns = row.getLastCellNum();
            for (int j = 0; j < columns; j++) {
                XSSFCell cell = row.getCell(j);
                if (row.getCell(j) == null) row.createCell(j);
                String content = cell.getRawValue();
                System.out.println(i + " " + j + " " + content);
            }
        }
    } else {
        return false;
    }
    return true;
}

@PostMapping("/import")
@ResponseBody
public void important(HttpServletRequest request, HttpServletResponse response) throws Exception {
    CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getServletContext());
    if (resolver.isMultipart(request)) { // 请求里包含文件流
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iterator = multipartHttpServletRequest.getFileNames(); // 获取所有文件名
        while (iterator.hasNext()) {
            MultipartFile multipartFile = multipartHttpServletRequest.getFile(iterator.next()); // 读取文件流
            String fullName = multipartFile.getOriginalFilename(); // 获取文件全名
            String prefix = fullName.substring(0, fullName.lastIndexOf(".")).toLowerCase(); // 获取文件前缀
            String suffix = fullName.substring(fullName.lastIndexOf(".")).toLowerCase(); // 获取文件后缀
            String temporaryName = UUID.randomUUID().toString().replace("-", ""); // 临时文件名

            InputStream inputStream = null;
            FileOutputStream fileOutputStream = null;
            try {
                File temporaryFile = File.createTempFile(temporaryName, suffix); // 创建临时文件
                multipartFile.transferTo(temporaryFile); // 文件流转化为文件
                if (suffix.equals("zip") || suffix.equals("rar")) {
                    ZipFile zip = new ZipFile(temporaryFile, Charset.forName("GBK")); //解决中文文件夹乱码
                    for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); ) {
                        ZipEntry entry = entries.nextElement(); // 压缩文件实体
                        String outputPath = "D:/" + entry.getName(); // 文件输出路径
                        File outputFile = new File(outputPath); // 输出文件
                        if(entry.isDirectory()){
                            outputFile.mkdirs(); // 创建任意层级的目录
                        }else{
                            outputFile.createNewFile(); // 创建文件
                            inputStream = zip.getInputStream(entry); // 获取压缩文件输入流
                            fileOutputStream = new FileOutputStream(outputFile); // 创建文件输出流
                            byte[] bytes = new byte[1024];
                            int length;
                            while ((length = inputStream.read(bytes)) > 0) { // 输入流读入数组
                                fileOutputStream.write(bytes, 0, length); // 数组写出输出流
                            }
                        }
                    }
                }
                inputStream.close(); // 释放输入流
                fileOutputStream.close(); // 释放输出流
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(inputStream != null){
                    inputStream.close(); // 释放输入流
                }
                if(fileOutputStream != null){
                    fileOutputStream.close(); // 释放输出流
                }
            }
        }
    }

    Map<String,Object> map = new HashMap<>();
    map.put("code",200);
    map.put("msg","操作成功");
    response.setContentType("application/json;charset=utf-8");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();
    out.print(JSON.toJSONString(map));
    out.flush();
}
三、导出
@RequestMapping(value = "/export", method = RequestMethod.GET)
@ResponseBody
public boolean export(HttpServletResponse response) throws Exception {
    HSSFWorkbook workbook = new HSSFWorkbook(); -> EXCEL的文档对象
    HSSFSheet sheet = workbook.createSheet("sheet"); -> EXCEL的工作簿
    HSSFCellStyle cellStyle = workbook.createCellStyle(); -> EXCEL的单元格样式
    cellStyle.setAlignment(HorizontalAlignment.CENTER); -> 设置水平居中
    cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); -> 设置垂直居中
    HSSFFont font = workbook.createFont(); -> 单元格字体
    font.setColor(HSSFFont.COLOR_RED);
    cellStyle.setFont(font);
    for (int i = 0; i < 10; i++) {
        HSSFRow row = sheet.createRow(i); -> EXCEL的行
        for (int j = 0; j < 10; j++) {
            HSSFCell cell = row.createCell(j); -> EXCEL的行的单元格
            cell.setCellValue(i + " " + j); -> 设置单元格里的值
            cell.setCellType(CellType.STRING); -> 设置单元格内容格式
            cell.setCellStyle(cellStyle); -> 设置单元格样式
        }
        sheet.setColumnWidth(i, 256 * 10); -> 设置表单列宽
    }
    String name = URLEncoder.encode("EXCEL表格", "UTF-8");
    response.setHeader("Content-type", "text/html;charset=UTF-8"); -> 客户端输出流
    response.setHeader("Content-disposition", "attachment;filename=" + name + ".xls"); -> 激活文件下载框
    response.setContentType("application/ms-excel"); -> 导出EXCEL类型
    OutputStream stream = response.getOutputStream();
    workbook.write(stream);
    workbook.close();
    return true;
}

window.location.href = '/export'; -> 前端通过href属性激活浏览器下载框
var $thead = $("#bootstrap-table thead div[class=th-inner]"); -> 表头
var $tbody = $("#bootstrap-table tbody tr"); -> 表列
var application = "application/vnd.ms-excel"; -> xls文件格式

var excel = '<table>' + '<tr>';
for (var i = 0; i < $thead.length; i++) {
  excel += '<td>' + $thead.eq(i).text() + '</td>';
}
excel += '</tr>';
for (var i = 0; i < $tbody.length; i++) {
  excel += '<tr>';
  var $td = $tbody.eq(i).find('td:not(:has( > div))');
  for (var j = 0; j < $td.length; j++) {
    excel += '<td>' + $td.eq(j).text() + '</td>';
    }
  excel += '</tr>';
}
excel += '</table>';

var excelFile = '<html xmlns:o=\'urn:schemas-microsoft-com:office:office\' ';
excelFile += 'xmlns:x=\'urn:schemas-microsoft-com:office:excel\' ';
excelFile += 'xmlns=\'http://www.w3.org/TR/REC-html40\'>';
excelFile += '<meta http-equiv="content-type" content="' + application + '; charset=UTF-8">';
excelFile += '<head>';
excelFile += '<!--[if gte mso 9]>';
excelFile += '<xml>';
excelFile += '<x:ExcelWorkbook>';
excelFile += '<x:ExcelWorksheets>';
excelFile += '<x:ExcelWorksheet>';
excelFile += '<x:Name>';
excelFile += '{worksheet}';
excelFile += '</x:Name>';
excelFile += '<x:WorksheetOptions>';
excelFile += '<x:DisplayGridlines/>';
excelFile += '</x:WorksheetOptions>';
excelFile += '</x:ExcelWorksheet>';
excelFile += '</x:ExcelWorksheets>';
excelFile += '</x:ExcelWorkbook>';
excelFile += '</xml>';
excelFile += '<![endif]-->';
excelFile += '</head>';
excelFile += '<body>';
excelFile += excel;
excelFile += '</body>';
excelFile += '</html>';

var uri = 'data:' + application + ';charset=utf-8,' + encodeURIComponent(excelFile);
var link = document.createElement('a');
link.href = uri;
$(link).css("visibility", "hidden");
$(link).attr("download", '模板.xls');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
OFFICE MIME Type
.doc application/msword
.dot application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm application/vnd.ms-word.document.macroEnabled.12
.dotm application/vnd.ms-word.template.macroEnabled.12
.xls application/vnd.ms-excel
.xlt application/vnd.ms-excel
.xla application/vnd.ms-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm application/vnd.ms-excel.sheet.macroEnabled.12
.xltm application/vnd.ms-excel.template.macroEnabled.12
.xlam application/vnd.ms-excel.addin.macroEnabled.12
.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12
.ppt application/vnd.ms-powerpoint
.pot application/vnd.ms-powerpoint
.pps application/vnd.ms-powerpoint
.ppa application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm application/vnd.ms-powerpoint.presentation.macroEnabled.12
.ppsm application/vnd.ms-powerpoint.slideshow.macroEnabled.12
四、下载模板
try { -> 请求后端接口
  InputStream inputStream = (InputStream) this.getClass()
  .getClassLoader().getResourceAsStream("mould.xlsx");
  response.setContentType("application/zip");
  OutputStream out = response.getOutputStream();
  response.setHeader("Content-Disposition","attachment;filename=mould.xlsx");
  int b = 0;
  byte[] buffer = new byte[1000000];
  while (b != -1) {
    b = inputStream.read(buffer);
    if(b!=-1) out.write(buffer, 0, b);
  }
  inputStream.close();
  out.close();
  out.flush();
  } catch (IOException e) {
    e.printStackTrace();
}
文件存放位置(SpringBoot):resource/mould.xlsx

<a href='/localhost:8080/mould.xlsx'>点击下载模板</a> -> 前端访问文件位置
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,306评论 4 370
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,657评论 2 307
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,928评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,688评论 0 220
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,105评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,024评论 1 225
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,159评论 2 318
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,937评论 0 212
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,689评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,851评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,325评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,651评论 3 263
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,364评论 3 244
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,192评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,985评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,154评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,955评论 2 279

推荐阅读更多精彩内容