springboot+mybatis+vue導出指定的數據爲excel(包含圖片)

前端:

<el-button @click="speedupCheckbox" @current-change="handleSelectionChange">批量導出二維碼</el-button>

      handleSelectionChange (val) {
        this.multipleSelection = val
      },

      speedupCheckbox: function () {
        if (this.multipleSelection.length === 0) {
          this.$message({
            message: '請至少勾選一項,再進行操作',
            type: 'warning'
          })
        } else {
          this.exportData()
        }
      },

exportCodeData () {
        this.$confirm('此操作將無法撤回, 是否繼續?', '提示', {
          confirmButtonText: '確定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let arr = this.multipleSelection
          let multis = []
          for (let i = 0; i < arr.length; i++) {
            multis.push(arr[i].id)
            console.log(multis)
          }
          axios({
            method: 'POST',
            url: Config.context + '/userManager/exportData',
            data: multis,
            responseType: 'blob'
          }).then(response => {
            if (!response) {
              return
            }
            const blob = new Blob([response.data])
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, '數據_.xls')
            } else {
              let u = window.URL.createObjectURL(response.data)
              let aLink = document.createElement('a')
              aLink.style.display = 'none'
              aLink.href = u
              aLink.setAttribute('download', '數據_.xls')
              document.body.appendChild(aLink)
              aLink.click()
              document.body.removeChild(aLink)
              window.URL.revokeObjectURL(u)
            }
          }).catch(error => {
            throw error
          })
          this.$refs.multipleTable.clearSelection()            // 操作完成清除勾選框
        })
      }


後端controller:

    @RequestMapping("/exportData")
    public void exportHandConf(@RequestBody List<String> data, HttpServletRequest request,
                                                   HttpServletResponse response)
    {

        //查詢需要導出的數據
        List<xxx> data1 = xxxDao.find(data);

        if (data1.size() != 0)
        {
            try
            {
                String title = "信息";
                String[] rowsName = new String[] { "序號","二維碼", "暱稱"};
                List<Object[]> dataList = new ArrayList<>();
                Object[] objs = null;
                for (int i = 0; i < data1.size(); i++)
                {
                    objs = new Object[rowsName.length];
                    objs[0] = i;
                    objs[1] = data1.get(i).getGroup_code();
                    objs[2] = data1.get(i).getNickname();

                    dataList.add(objs);
                }
                ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, dataList, response);
                ex.exportData();
            }
            catch (Exception e)
            {
                e.printStackTrace();

            }

        }

    }

這裏面是個動態sql:

xml:

    <select id="find" parameterType="java.util.List" resultType="實體類路徑">
        select * from xxx where 1 = 1
        <if test="xx!= null and xx.size() > 0">
            AND
            <foreach collection="xx" item="xxx" open="xxx in(" close=")" separator=",">
                #{xxx}
            </foreach>
        </if>
    </select>

dao:

    List<xxx> find(@Param("xx") List<String> xxx);

service:

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * poi導出
 * @author yangjaibin
 *
 */
public class ExportExcelUtils {
    private String title; // 導出表格的表名

    private String[] rowName;// 導出表格的列名

    private List<Object[]> dataList = new ArrayList<Object[]>(); // 對象數組的List集合

    private HttpServletResponse response;

    // 傳入要導入的數據
    public ExportExcelUtils(String title, String[] rowName, List<Object[]> dataList, HttpServletResponse response)
    {
        this.title = title;
        this.rowName = rowName;
        this.dataList = dataList;
        this.response = response;
    }

    // 導出數據
    public void exportData()
    {
        try
        {
            HSSFWorkbook workbook = new HSSFWorkbook(); // 創建一個excel對象
            HSSFSheet sheet = workbook.createSheet(title); // 創建表格
            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
            // 產生表格標題行
            HSSFRow rowm = sheet.createRow(0);  // 行
            HSSFCell cellTiltle = rowm.createCell(0);  // 單元格
            // sheet樣式定義
            HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook); // 頭樣式
            HSSFCellStyle style = this.getStyle(workbook);  // 單元格樣式
            /**
             * 參數說明
             * 從0開始   第一行 第一列 都是從角標0開始
             * 行 列 行列    (0,0,0,5)  合併第一行 第一列  到第一行 第六列
             * 起始行,起始列,結束行,結束列
             *
             * new Region()  這個方法使過時的
             */
            // 合併第一行的所有列
            sheet.addMergedRegion(new CellRangeAddress(0, (short) 0, 0, (short) (rowName.length - 1)));
            cellTiltle.setCellStyle(columnTopStyle);
            cellTiltle.setCellValue(title);

            int columnNum = rowName.length;  // 表格列的長度
            HSSFRow rowRowName = sheet.createRow(1);  // 在第二行創建行
            HSSFCellStyle cells = workbook.createCellStyle();
            cells.setBottomBorderColor(HSSFColor.BLACK.index);
            rowRowName.setRowStyle(cells);

            // 循環 將列名放進去
            for (int i = 0; i < columnNum; i++)
            {
                HSSFCell cellRowName = rowRowName.createCell((int) i);
                cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 單元格類型

                HSSFRichTextString text = new HSSFRichTextString(rowName[i]);  // 得到列的值
                cellRowName.setCellValue(text); // 設置列的值
                cellRowName.setCellStyle(columnTopStyle); // 樣式
            }

            // 將查詢到的數據設置到對應的單元格中
            for (int i = 0; i < dataList.size(); i++)
            {
                Object[] obj = dataList.get(i);//遍歷每個對象
                HSSFRow row = sheet.createRow(i + 2);//創建所需的行數
                row.setHeightInPoints(40);

                for (int j = 0; j < obj.length; j++)
                {
                    HSSFCell cell = null;   //設置單元格的數據類型
                    if (j == 0)
                    {
                        // 第一列設置爲序號
                        cell = row.createCell(j);
                        cell.setCellValue(i + 1);
                    }
                    else
                    {
                        cell = row.createCell(j);

                        if (!"".equals(obj[j]) && obj[j] != null)
                        {
                            if (obj[j].toString().length() > 30)
                            {
                                cell.setCellValue("  ");
                                drawPictureInfoExcel(workbook, patriarch, obj[j].toString(), i + 2);//i+2代表當前的行
                            }
                            else
                            {
                                cell.setCellValue(obj[j].toString());
                            }
                            //設置單元格的值
                        }
                        else
                        {
                            cell.setCellValue("  ");
                        }

                    }
                    cell.setCellStyle(style); // 樣式
                }
            }
            //  讓列寬隨着導出的列長自動適應

            sheet.setColumnWidth(0, 8 * 256);  //調整第一列寬度
            sheet.setColumnWidth(1, 8 * 256);
            sheet.setColumnWidth(2, 20 * 256);  ///調整第二列寬度
            sheet.setColumnWidth(3, 20 * 256);
            sheet.setColumnWidth(4, 20 * 256);
            sheet.setColumnWidth(5, 21 * 256);
            sheet.setColumnWidth(6, 20 * 256);

            if (workbook != null)
            {
                try
                {
                    // excel 表文件名
                    String fileName = title + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
                    String fileName11 = URLEncoder.encode(fileName, "UTF-8");
                    String fileName12 = URLDecoder.decode(fileName11, "UTF-8");
                    String headStr = "attachment; filename=\"" + fileName12 + "\"";
                    response.setContentType("APPLICATION/OCTET-STREAM");
                    // response.setHeader("Content-Disposition", headStr);
                    response.setHeader("Content-Disposition",
                            "attachment;filename=" + new String(fileName12.getBytes("gb2312"), "ISO8859-1"));
                    OutputStream out = response.getOutputStream();
                    workbook.write(out);
                    out.flush();
                    out.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }

            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    private void drawPictureInfoExcel(HSSFWorkbook wb, HSSFPatriarch patriarch, String pictureUrl, int rowIndex)
    {
        //rowIndex代表當前行
        try
        {
            if (pictureUrl != null)
            {

//                URL url = new URL(pictureUrl);//獲取人員照片的地址
//                //打開鏈接
//                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//                //設置請求方式爲"GET"
//                conn.setRequestMethod("GET");
//                //超時響應時間爲5秒
//                conn.setConnectTimeout(5 * 1000);
//                //通過輸入流獲取圖片數據
//                InputStream inStream = conn.getInputStream();
                //得到圖片的二進制數據,以二進制封裝得到數據,具有通用性
                BASE64Decoder decoder =new BASE64Decoder();

                byte[] data = decoder.decodeBuffer(pictureUrl);
//                byte[] data = readInputStream(inStream);
                //anchor主要用於設置圖片的屬性
                HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 1, rowIndex, (short) 1,
                        rowIndex);
                //Sets the anchor type (圖片在單元格的位置)
                //0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.
                anchor.setAnchorType(0);
                patriarch.createPicture(anchor, wb.addPicture(data, HSSFWorkbook.PICTURE_TYPE_JPEG));
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private static byte[] readInputStream(InputStream inStream) throws Exception
    {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //創建一個Buffer字符串
        byte[] buffer = new byte[1024];
        //每次讀取的字符串長度,如果爲-1,代表全部讀取完畢
        int len = 0;
        //使用一個輸入流從buffer裏把數據讀取出來
        while ((len = inStream.read(buffer)) != -1)
        {
            //用輸出流往buffer裏寫入數據,中間參數代表從哪個位置開始讀,len代表讀取的長度
            outStream.write(buffer, 0, len);
        }
        //關閉輸入流
        inStream.close();
        //把outStream裏的數據寫入內存
        return outStream.toByteArray();
    }

    public HSSFCellStyle getStyle(HSSFWorkbook workbook)
    {
        // 設置字體
        HSSFFont font = workbook.createFont();
        //設置字體大小
        font.setFontHeightInPoints((short) 9);
        //字體加粗
        //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //設置字體名字
        font.setFontName("Courier New");
        //設置樣式;
        HSSFCellStyle style = workbook.createCellStyle();
        //設置底邊框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //設置底邊框顏色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //設置左邊框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //設置左邊框顏色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //設置右邊框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //設置右邊框顏色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //設置頂邊框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //設置頂邊框顏色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在樣式用應用設置的字體;
        style.setFont(font);
        //設置自動換行;
        style.setWrapText(false);
        //設置水平對齊的樣式爲居中對齊;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //設置垂直對齊的樣式爲居中對齊;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        return style;
    }

    public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook)
    {

        // 設置字體
        HSSFFont font = workbook.createFont();
        //設置字體大小
        font.setFontHeightInPoints((short) 10);
        //字體加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //設置字體名字
        font.setFontName("Courier New");
        //設置樣式;
        HSSFCellStyle style = workbook.createCellStyle();
        //設置底邊框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //設置底邊框顏色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //設置左邊框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //設置左邊框顏色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //設置右邊框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //設置右邊框顏色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //設置頂邊框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //設置頂邊框顏色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在樣式用應用設置的字體;
        style.setFont(font);
        //設置自動換行;
        style.setWrapText(false);
        //設置水平對齊的樣式爲居中對齊;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //設置垂直對齊的樣式爲居中對齊;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        return style;

    }

}

效果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章