生成 excel 直接用 httpServletResponse 輸出 超詳細的java生成excel文件並下載 超詳細的java生成excel文件並下載

  以前寫過一篇文章 《超詳細的java生成excel文件並下載》,該文章雖然夠詳細,也行得通,但仍是有必定的缺陷,該文章能夠拆分紅兩個部分,一是指定位置生成excel文件,二是根據地址下載文件。缺陷的部分是會產生中間文件,而這個中間文件咱們並不須要,若是每次下載的時候都會生成一個這樣的文件,那長此以往豈不是浪費空間,並且生成文件以後再讀取輸出這樣也耗時間。因此今天就對以前的文章進行優化處理下。html

        

package com.test.demo.controllers;

import com.test.demo.domain.entities.Address;
import com.test.demo.services.ExcelService;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.*;
import jxl.format.VerticalAlignment;
import jxl.write.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author dyh
 * @create 2018-11-15 下午10:20
 * @desc excle表格功能編寫
 **/
@RestController
@RequestMapping("/excel")
public class ExcelController {

    @Autowired
    private ExcelService excelService;

    /**
     * 下載文件
     *
     * @return
     */
    @RequestMapping({"/download"})
    public void download() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        HttpServletRequest request = requestAttributes.getRequest();

        // 文件名
        String filename = "地址列表.xls";
        OutputStream out = null;
        try {
       // 下面幾行是爲了解決文件名亂碼的問題
            httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "iso-8859-1"));
            httpServletResponse.setContentType("application/vnd.ms-excel;charset=UTF-8");
            httpServletResponse.setHeader("Pragma", "no-cache");
            httpServletResponse.setHeader("Cache-Control", "no-cache");
            httpServletResponse.setDateHeader("Expires", 0);
            out = httpServletResponse.getOutputStream();
            // 建立寫工做簿對象,這裏直接採用流輸出,而不會再生成一個文件
            WritableWorkbook workbook = Workbook.createWorkbook(out);
            // 工做表
            WritableSheet sheet = workbook.createSheet("地址列表", 0);
            // 設置字體;
            WritableFont font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);

            WritableCellFormat cellFormat = new WritableCellFormat(font);
            // 設置背景顏色;
            cellFormat.setBackground(Colour.WHITE);
            // 設置邊框;
            cellFormat.setBorder(Border.ALL, BorderLineStyle.DASH_DOT);
            // 設置文字居中對齊方式;
            cellFormat.setAlignment(Alignment.CENTRE);
            // 設置垂直居中;
            cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
            // 分別給1,5,6列設置不一樣的寬度;
            sheet.setColumnView(0, 15);
            sheet.setColumnView(4, 60);
            sheet.setColumnView(5, 35);
            // 給sheet電子版中全部的列設置默認的列的寬度;
            sheet.getSettings().setDefaultColumnWidth(20);
            // 給sheet電子版中全部的行設置默認的高度,高度的單位是1/20個像素點,但設置這個貌似就不能自動換行了
            // sheet.getSettings().setDefaultRowHeight(30 * 20);
            // 設置自動換行;
            cellFormat.setWrap(true);

            // 單元格
            Label label0 = new Label(0, 0, "ID", cellFormat);
            Label label1 = new Label(1, 0, "省", cellFormat);
            Label label2 = new Label(2, 0, "市", cellFormat);
            Label label3 = new Label(3, 0, "區", cellFormat);
            Label label4 = new Label(4, 0, "詳細地址", cellFormat);
            Label label5 = new Label(5, 0, "建立時間", cellFormat);

            sheet.addCell(label0);
            sheet.addCell(label1);
            sheet.addCell(label2);
            sheet.addCell(label3);
            sheet.addCell(label4);
            sheet.addCell(label5);

            // 給第二行設置背景、字體顏色、對齊方式等等;
            WritableFont font2 = new WritableFont(WritableFont.ARIAL, 14, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            WritableCellFormat cellFormat2 = new WritableCellFormat(font2);
            // 設置文字居中對齊方式;
            cellFormat2.setAlignment(Alignment.CENTRE);
            // 設置垂直居中;
            cellFormat2.setVerticalAlignment(VerticalAlignment.CENTRE);
            cellFormat2.setBackground(Colour.WHITE);
            cellFormat2.setBorder(Border.ALL, BorderLineStyle.THIN);
            cellFormat2.setWrap(true);

            // 記錄行數
            int n = 1;

            // 查找全部地址
            List<Address> addressList = excelService.findAll();
            if (addressList != null && addressList.size() > 0) {

                // 遍歷
                for (Address a : addressList) {

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String createTime = sdf.format(a.getCreateTime());

                    Label lt0 = new Label(0, n, a.getId() + "", cellFormat2);
                    Label lt1 = new Label(1, n, a.getProvince(), cellFormat2);
                    Label lt2 = new Label(2, n, a.getCity(), cellFormat2);
                    Label lt3 = new Label(3, n, a.getArea(), cellFormat2);
                    Label lt4 = new Label(4, n, a.getAddress(), cellFormat2);
                    Label lt5 = new Label(5, n, createTime, cellFormat2);

                    sheet.addCell(lt0);
                    sheet.addCell(lt1);
                    sheet.addCell(lt2);
                    sheet.addCell(lt3);
                    sheet.addCell(lt4);
                    sheet.addCell(lt5);

                    n++;
                }
            }

            //開始執行寫入操做
            workbook.write();
            //關閉流
            workbook.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}    

  上面的代碼就是關鍵的文件,至於一些其它的配置,以及可用的demo,可在前一篇文章 《超詳細的java生成excel文件並下載》 上下載下來稍稍一下。java

相關文章
相關標籤/搜索