1. 程式人生 > >web專案匯出excel表格

web專案匯出excel表格

  • 該功能涉及到兩個知識點,一是製作excel相關外掛的使用,二是匯出檔案,spring-mvc該如何配置
  • 先說excel外掛的使用,這次使用的是org.apache.poi包,版本是3.9,下面粘完整能執行的程式碼
  • maven依賴
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>
  • 外掛的實體類,也可以理解為引數,這裡採用了build設計模式,好處是初始化了一些預設值,使用的時候程式碼寫的方便。針對表格匯出,我覺得三個引數足夠了,標題、表頭以及資料,所以,這三個引數構造方法我設計的必傳,其它使用預設引數
package com.util;

import java.util.List;

public class ExcelParam {
    String name;
    int width;
    String font;
    String[] headers;
    /**
     * 匯出資料的樣式
     * 1:String left;
     * 2:String center
     * 3:String right
     * 4 int  right
     * 5:float ###,###.## right
     * 6:number: #.00% 百分比 right
     */
int[] ds_format; /** * 每列表格的寬度,預設為256 * 14 */ int[] widths; List<String[]> data; private ExcelParam() { } //使用Builder模式,設定預設引數和必填引數 public static class Builder { String name; int width = 256 * 14; String font = "微軟雅黑"; String[] headers; int
[] ds_format; int[] widths; List<String[]> data; public Builder(String name) { this.name = name; } public Builder font(String font) { this.font = font; return this; } public Builder width(int width) { this.width = width; return this; } public Builder headers(String[] headers) { this.headers = headers; return this; } public Builder ds_format(int[] ds_format) { this.ds_format = ds_format; return this; } public Builder widths(int[] widths) { this.widths = widths; return this; } public Builder data(List<String[]> data) { this.data = data; return this; } public ExcelParam build() { ExcelParam excelParam = new ExcelParam(); excelParam.name = this.name; excelParam.data = this.data; excelParam.widths = this.widths; excelParam.ds_format = this.ds_format; excelParam.headers = this.headers; excelParam.font = this.font; excelParam.width = this.width; return excelParam; } } }
  • 外掛本身
package com.ucredit.util;

import org.apache.poi.hssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

public class ExcelUtil {
    private ExcelUtil() {
    }

    public static void export(ExcelParam excelParam, HttpServletResponse response) throws IOException {
        if (excelParam.widths == null) {
            excelParam.widths = new int[excelParam.headers.length];
            for (int i = 0; i < excelParam.headers.length; i++) {
                excelParam.widths[i] = excelParam.width;
            }
        }
        if (excelParam.ds_format == null) {
            excelParam.ds_format = new int[excelParam.headers.length];
            for (int i = 0; i < excelParam.headers.length; i++) {
                excelParam.ds_format[i] = 1;
            }
        }
        //建立一個工作薄
        HSSFWorkbook wb = new HSSFWorkbook();
        //建立一個sheet
        HSSFSheet sheet = wb.createSheet("excel");
        int rowCount = 0;
        if (excelParam.headers != null) {
            HSSFRow row = sheet.createRow(rowCount);
            //表頭樣式
            HSSFCellStyle style = wb.createCellStyle();
            HSSFFont font = wb.createFont();
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            font.setFontHeightInPoints((short) 11);
            style.setFont(font);
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

            for (int i = 0; i < excelParam.headers.length; i++) {
                sheet.setColumnWidth(i, excelParam.widths[i]);
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(excelParam.headers[i]);
                cell.setCellStyle(style);
            }
            rowCount++;
        }
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //表格主體  解析list
        for (int i = 0; i < excelParam.data.size(); i++) {  //行數
            HSSFRow row = sheet.createRow(rowCount);
            for (int j = 0; j < excelParam.headers.length; j++) {  //列數
                HSSFCell cell = row.createCell(j);
                cell.setCellValue(excelParam.data.get(i)[j]);
                cell.setCellStyle(style);
            }
            rowCount++;
        }
        //設定檔名
        String fileName = excelParam.name + ".xls";
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Pragma", "No-cache");
        OutputStream outputStream = response.getOutputStream();
        wb.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
  • 其實從這個方法就能看出,檔案最後匯出,實際上是往response中的outputStream中寫入檔案,之後的工作是由瀏覽器來完成的
  • controller層寫法
    @RequestMapping(value = "download")
    public void download(@RequestParam String username,
                         @RequestParam String operation_module,
                         @RequestParam String operation_type,
                         @RequestParam String start_time,
                         @RequestParam String end_time,
                         HttpServletResponse response) throws Exception {
        List<OperationLogEntity> list = operationLogDao.get(username, operation_module, operation_type, start_time, end_time);
        String[] heads = {"序號", "賬號", "姓名", "操作型別", "操作模組", "處理員工號碼", "處理結果", "登入IP", "時間", "所在城市"};
        List<String[]> data = new LinkedList<>();
        for (int i = 0; i < list.size(); i++) {
            OperationLogEntity entity = list.get(i);
            String[] temp = new String[10];
            temp[0] = String.valueOf(i + 1);
            temp[1] = entity.getUsername();
            temp[2] = entity.getName();
            temp[3] = entity.getOperation_type();
            temp[4] = entity.getOperation_module();
            temp[5] = entity.getProcess_number();
            temp[6] = entity.getProcess_result();
            temp[7] = entity.getIp();
            temp[8] = DateUtils.getDateBeforeOrAfterStrCN(entity.getOperation_time(), 0);
            temp[9] = entity.getCity();
            data.add(temp);
        }
        ExcelParam param = new ExcelParam.Builder("操作日誌").headers(heads).data(data).build();
        ExcelUtil.export(param, response);
    }
  • 實際使用
//這樣寫很簡潔
ExcelParam param = new ExcelParam.Builder("操作日誌").headers(heads).data(data).build();

相關推薦

web專案匯出excel表格

該功能涉及到兩個知識點,一是製作excel相關外掛的使用,二是匯出檔案,spring-mvc該如何配置 先說excel外掛的使用,這次使用的是org.apache.poi包,版本是3.9,下面粘完整能執行的程式碼 maven依賴 <dependenc

Java Web專案匯出Excel的實現

背景:本次實現基於原生JDBC連線資料庫、Struts2框架。 1.JDBC連線資料庫部分比較簡單,就不詳細介紹,簡述:建立一個JavaBean類,連線資料庫獲取該JavaBean物件的集合; 2.建立通用工具類,用於生成Excel模板: import org.apache.poi.hssf.

Java Web專案匯出excel表,位址列中文正常,但是檔案下載報404中文檔名亂碼

最近,在公司做專案遇到的問題,解決了很長時間。總結一下。 使用的是easyui前臺框架,後臺是spring+jdbc。問題是:匯出excel表時,出現錯誤,報404.如下圖所示: 我們可以看到,在下載excel表時,位址列沒有問題,且中文檔名正常顯示。如中文檔名出現亂碼,

Java web專案利用POI匯出EXCEL表格

SSH2 POI匯出EXCEL表格 1.首先匯入poi的jar包 HSSFWorkbook :工作簿,代表一個excel的整個文件 HSSFSheet:工作表 HSSFRow :行 HSSFCell:單元格 HSSFCellStyle :單元格樣

web專案實現Excel資料匯入匯出

        由於專案要求,需要實現一個數據庫資訊匯出為Excel檔案,並能將Excel檔案中的資訊匯入資料庫的功能,網上找了一下資料,發現大都只涉及到Excel檔案的簡單操作,所以特地在此分享了自己寫的兩個簡單的Web端Excel檔案匯入匯出的例子。         涉

vue專案實現表格匯出excel表格

第一:安裝依賴 npm install -S file-saver xlsx npm install -D script-loader 第二:在目錄裡新建excel資料夾 在excel資料夾裡新建兩個js檔案(Blob.js和Export2Excel.js) Blob.js

POI匯出excel表格優化

package com.ywj.excel; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java

HSSFWorkbook(poi)匯出excel表格

本文與另一篇文章關聯: csv格式匯出excel報表 其中: String accountDate 入參(日期) AccountInfoEntityResp accountInfoEntityResp 匯出的xml報文內容(轉換成obj物件) xml報文解析見另一篇:x

json字元陣列轉List+匯出Excel表格

 首先是json字元陣列轉List集合物件 String jsonString = custIcCardDubboService.getExcelFailData(keyName); List<CardExcelVo> excelVoList = JSON.pars

IE中在js中將查詢出的資料匯出excel表格

<input style="width: 70px; height: 22px;margin-left: 10%;font-family: \"微軟雅黑\" ; font-size: 12px; color:#2587D2 " type="button" onclick="move('exec

post請求匯出Excel表格

axios. interceptors. response. use(( response) =>{ if( response. config && response. config.

vue匯出Excel表格(通用)

封裝匯出的js程式碼 // 獲取cookie、 export function getCookie (name) { if (document.cookie.length > 0){ let c_start = document.cookie.indexOf(name +

PHP 匯出excel表格 數字字串過長 無法顯示完全

php程式將資料匯出至excel表格時發現一個問題,若字串過長會自動轉換為科學計數法。解決此問題只需在新增excel值時拼接一個製表符 如 //值拼接製表符 $value = $value."\t"; require_once __DIR__ . '/./PHPExcel/Classes/

機房---不同窗體呼叫模組中匯出excel表格的程式碼

第一步: Public c As Form 第二步:注意c的位置 Public Sub export() Dim xlapp As Excel.Application '宣告excel物件 Dim xlbook As Excel.Workboo

Java匯入匯出Excel表格(xls版本、xlsx版本)

自己整合成的一個專門匯入匯出工具類 一、pom檔案導包: <!-- 匯入匯出Excel表格 --> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <depend

FineReport 報表模板生成+匯出Excel表格

看官方的文件糾結了一天,好東西,這個怎麼下手,但是還是想總結一下。 FineReport報表技術,給我的感覺跟IReport報表的思路差不多,所以我就抱著這種試試的心態去嘗試,在我搜集資料加看官方文件之後,覺得更像了!!! FineReport報表軟體是一款純java編寫的,集資料展示(報表

c#/.net 匯出excel表格

1.本片主要講述excel匯出的樣式處理,匯出方法看前一篇 static void Main(string[] args) { List<ExportModel> list = new List<ExportModel>(); string[] types = new string

poi-匯出excel表格

1.效果圖 2.Java程式碼 /** * * @Title: exportExcel * @Description: 匯出excel * @param request * @param response * @return * @throws Exce

vue中匯出Excel表格

專案中我們可能會碰到匯出Excel檔案的需求,一般後臺管理系統中居多,將table中展示的資料匯出儲存到本地。當然我們也可以通過一些處理來修改要匯出的資料格式,具體需求具體對待。 1、首先我們需要安裝3個依賴,file-saver、xlsx和script-loade

使用POI匯出EXCEL表格

1.工具類 public class ExcelUtil { @SuppressWarnings("deprecation") public static void createCell(HSSFCellStyle cellstyle, HSSFRow ro