超詳細的java生成excel文件並下載

在網上隨手一搜,能夠搜到不少java生成excel文件相關的博客,但每一個都有不一樣,核心點說清楚了,但具體運用的時候,相信你們或多或少都無法一次直接運用,這樣每次去找而且運用的時候很費時間,因此這也是我以爲有必要寫這個博客的緣由java

 

一、導入所須要的jar包mysql

<!-- excel 引用包 -->
<dependency>
   <groupId>net.sourceforge.jexcelapi</groupId>
    <artifactId>jxl</artifactId>
    <version>2.6.12</version>
</dependency>

 

二、編寫所須要的類linux

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-07-14 下午8: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";

        try {

            // 寫到服務器上
            String path = request.getSession().getServletContext().getRealPath("") + "/" + filename;

            // 寫到服務器上(這種測試過,在本地能夠,放到linux服務器就不行)
            //String path =  this.getClass().getClassLoader().getResource("").getPath()+"/"+filename;

            File name = new File(path);
            // 建立寫工做簿對象
            WritableWorkbook workbook = Workbook.createWorkbook(name);
            // 工做表
            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();

        } catch (Exception e) {
            e.printStackTrace();
        }
        // 第六步,下載excel

        OutputStream out = null;
        try {

            // 1.彈出下載框,並處理中文
            /** 若是是從jsp頁面傳過來的話,就要進行中文處理,在這裏action裏面產生的直接能夠用
             * String filename = request.getParameter("filename");
             */
            /**
             if (request.getMethod().equalsIgnoreCase("GET")) {
             filename = new String(filename.getBytes("iso8859-1"), "utf-8");
             }
             */

            response.addHeader("content-disposition", "attachment;filename="
                    + java.net.URLEncoder.encode(filename, "utf-8"));

            // 2.下載
            out = response.getOutputStream();
            String path3 = request.getSession().getServletContext().getRealPath("") + "/" + filename;

            // inputStream:讀文件,前提是這個文件必須存在,要不就會報錯
            InputStream is = new FileInputStream(path3);

            byte[] b = new byte[4096];
            int size = is.read(b);
            while (size > 0) {
                out.write(b, 0, size);
                size = is.read(b);
            }
            out.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

package com.test.demo.services;

import com.test.demo.domain.entities.Address;
import com.test.demo.domain.entities.AddressRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author dyh
 * @create 2018-07-14 下午9:21
 * @desc excel測試類
 **/

@Service
public class ExcelService {

    @Autowired
    private AddressRepository addressRepository;

    /**
     * 獲得全部地址列表
     *
     * @return
     */
    public List<Address> findAll(){
        return addressRepository.findAll();
    }
}

 

三、配置文件git

server.port=8025

spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=1
spring.datasource.initial-size=1
spring.datasource.validation-query=SELECT 1
spring.datasource.test-on-borrow=false
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=18800

spring.datasource.url=@db.dyh2020.url@
spring.datasource.username=@db.dyh2020.username@
spring.datasource.password=@db.dyh2020.password@
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.database=MYSQL
# 顯示後臺處理的SQL語句
spring.jpa.show-sql=true
# 自動檢查實體和數據庫表是否一致,若是不一致則會進行更新數據庫表
spring.jpa.hibernate.ddl-auto=none

 

寫好代碼以後本地運行,在瀏覽器輸入地址:http://localhost:8025/excel/download  便可看到下載的文件github

 

github代碼地址:https://github.com/DYH2020/springBootDemoweb

相關文章
相關標籤/搜索