Java 導入數據到Excel並提供文件下載接口

最近的項目中遇到了一個將數據庫的信息導入到一個 Excel 文件的需求,並且還要提供下載該 Excel 文件的接口 ,搞定以後,進行了一下總結,但願給你們帶來幫助git

源碼: github.com/HowieYuan/E…github

依賴

<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
<dependency>
	<groupId>net.sourceforge.jexcelapi</groupId>
	<artifactId>jxl</artifactId>
	<version>2.6.12</version>
</dependency>
複製代碼

咱們須要用到 jxl 包的類,而 jxl.jar 正是操做 excel 表格的工具類庫,除了 jxl 之外,poi 包也是一個 操做 excel 的類庫。
而對比兩個包,jxl 更適用與數據量大的狀況,而 poi 在數據量不高(大約5000之內)時,效率較高,但佔用內存大,更容易內存溢出。數據庫

測試數據

private int id;
private String name;
private int age;
private String gender;
複製代碼
public List<Person> getPersonList() {
    List<Person> list = new ArrayList<>();
    list.add(new Person(1, "Howie", 20, "female"));
    list.add(new Person(2, "Wade", 25, "male"));
    list.add(new Person(3, "Duncan", 30, "male"));
    list.add(new Person(4, "Kobe", 35, "male"));
    list.add(new Person(5, "James", 40, "male"));
    return list;
}
複製代碼

1. 將數據所有導入到一張表格

//建立文件本地文件
//直接將文件建立在項目目錄中
String filePath = "人員數據.xlsx";
File dbfFile = new File(filePath);
//使用 Workbook 類的工廠方法建立一個可寫入的工做薄(Workbook)對象
WritableWorkbook wwb = Workbook.createWorkbook(dbfFile);
//若是文件不存在,則建立一個新的文件
if (!dbfFile.exists() || dbfFile.isDirectory()) {
    dbfFile.createNewFile();
}
//得到人員信息 list (PersonFactroy 類已經被依賴注入)
List<Person> list = personFactroy.getPersonList();
 //建立一個可寫入的工做表
WritableSheet ws = wwb.createSheet("列表 1", 0); 
//添加excel表頭
ws.addCell(new Label(0, 0, "序號"));
ws.addCell(new Label(1, 0, "姓名"));
ws.addCell(new Label(2, 0, "年齡"));
ws.addCell(new Label(3, 0, "性別"));
int index = 0;
for (Person person : list) {
    //將生成的單元格添加到工做表中
    //(這裏須要注意的是,在Excel中,第一個參數表示列,第二個表示行)
    ws.addCell(new Label(0, index + 1, String.valueOf(person.getId())));
    ws.addCell(new Label(1, index + 1, person.getName()));
    ws.addCell(new Label(2, index + 1, String.valueOf(person.getAge())));
    ws.addCell(new Label(3, index + 1, person.getGender()));
    index++;
}
複製代碼

導入數據後的 Excel 表

2. 將數據導入到多個表格

//前面的代碼一致

//每一個工做表格最多存儲2條數據(注:excel表格一個工做表能夠存儲65536條)
int mus = 2; 
//數據的總大小
int totle = list.size();
//總表格數
int avg = totle / mus + 1;
for (int i = 0; i < avg; i++) {
    //建立一個可寫入的工做表
    WritableSheet ws = wwb.createSheet("列表" + (i + 1), i);  
    //添加excel表頭
    ws.addCell(new Label(0, 0, "序號"));
    ws.addCell(new Label(1, 0, "姓名"));
    ws.addCell(new Label(2, 0, "年齡"));
    ws.addCell(new Label(3, 0, "性別"));
    int num = i * mus;
    int index = 0;
    for (int m = num; m < list.size(); m++) {
        //判斷index == mus的時候跳出當前for循環
        if (index == mus) {
            break;
        }
        Person person = list.get(m);
        //將生成的單元格添加到工做表中
        //(這裏須要注意的是,在Excel中,第一個參數表示列,第二個表示行)
        ws.addCell(new Label(0, index + 1, String.valueOf(person.getId())));
        ws.addCell(new Label(1, index + 1, person.getName()));
        ws.addCell(new Label(2, index + 1, String.valueOf(person.getAge())));
        ws.addCell(new Label(3, index + 1, person.getGender()));
        index++;
    }
}
複製代碼

這裏是根據每一個表的數據量來分,你們也能夠根據其中一個屬性等等來分紅各個表格api

提供文件下載接口

該方法利用文件流來寫入文件,方法類型爲 void,不須要 return,除此以外,接口參數中須要添加上 HttpServletResponsebash

@RequestMapping(value = "/getExcel", method = RequestMethod.GET)
    public void createBoxListExcel(HttpServletResponse response) throws Exception {
        String filePath = "人員數據.xlsx";
        
        /**
         *  這部分是剛剛導入 Excel 文件的代碼,省略
         */
        
        String fileName = new String("人員數據.xlsx".getBytes(), "ISO-8859-1");
        //設置文件名
        response.addHeader("Content-Disposition", "filename=" + fileName);
        OutputStream outputStream = response.getOutputStream();
        FileInputStream fileInputStream = new FileInputStream(filePath);
        byte[] b = new byte[1024];
        int j;
        while ((j = fileInputStream.read(b)) > 0) {
            outputStream.write(b, 0, j);
        }
        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
    }
複製代碼

而後,咱們直接在地址欄輸入localhost:8080/getExcel既可馬上下載你的文件app

注意: String fileName = new String("人員信息.xlsx".getBytes(), "ISO-8859-1"); 我使用了 ISO-8859-1 編碼,緣由是 ISO-8859-1編碼是單字節編碼,向下兼容 ASCII,而 Header 中只支持 ASCII,傳輸的文件名必須是 ASCII工具

相關文章
相關標籤/搜索