Jfinal 導出Excel(1)


本篇介紹基於JFinal將列表導出成Excel

JFinal導出Excel

Apache POI

Apache POIApache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能。

結構:

  • HSSF - 提供讀寫Microsoft Excel XLS格式檔案的功能。

  • XSSF - 提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能。

  • HWPF - 提供讀寫Microsoft Word DOC97格式檔案的功能。

  • XWPF - 提供讀寫Microsoft Word DOC2003格式檔案的功能。

  • HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能。

  • HDGF - 提供讀Microsoft Visio格式檔案的功能。

  • HPBF - 提供讀Microsoft Publisher格式檔案的功能。

  • HSMF - 提供讀Microsoft Outlook格式檔案的功能。

Maven地址:


<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>

導出Excel

添加Excel操作類,XLSFileKit


package common.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class XLSFileKit {

    // 創建一個`excel`文件
	private HSSFWorkbook workBook;
	
    // `excel`文件保存路徑
	private String filePath;
	public XLSFileKit(String filePath){
		this.filePath=filePath;
		this.workBook=new HSSFWorkbook();
	}
	
	/**
	 * 添加sheet
	 * @param content 數據
	 * @param sheetName sheet名稱
	 * @param title 標題
	 */
	public <T> void addSheet(List<List<T>> content,String sheetName,List<String> title){
		HSSFSheet sheet=this.workBook.createSheet(sheetName);
		
		// `excel`中的一行
    	HSSFRow row=null;
		
		// `excel`中的一個單元格
    	HSSFCell cell=null;
    	int i=0,j=0;
		
		// 創建第一行,添加`title`
    	row=sheet.createRow(0);
    	for(;j<title.size();j++){//添加標題
    		cell=row.createCell(j);
			cell.setCellValue(title.get(j));
    	}
		
		// 創建余下所有行
    	i=1;
    	for(List<T> rowContent:content){
    		row=sheet.createRow(i);
    		j=0;
    		for(Object cellContent:rowContent){
    			cell=row.createCell(j);
    			cell.setCellValue(cellContent.toString());
    			j++;
    		}
    		i++;
    	}
	}
	
	/**
	 * 保存
	 * @return
	 */
	public boolean save(){
		try {
			FileOutputStream fos=new FileOutputStream(this.filePath);
			this.workBook.write(fos);
			fos.close();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	return false;
	}
}


添加ExportExcelController:


package controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import common.util.XLSFileKit;
import service.ExportExcelService;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;


public class ExportExcelController extends Controller{

    // 和`ExportExcelController`對應的`Service`類
	ExportExcelService exportExcelService = new ExportExcelService();
	
	/**
	 * 導出表格
	 */
	public void exportOutExcel(){
		String sheetName = getPara("sheetName");		
		
		// 導出`Excel`名稱
		String fileName = new Date().getTime() + "_" + UUID.randomUUID().toString() + ".xls";
		
		// excel`保存路徑
		String filePath = getRequest().getRealPath("/") + "/file/export/";
		File file = new File(filePath);
		if(!file.exists()){
			file.mkdirs();
		}
		String relativePath = "/file/export/" + fileName;
		filePath += fileName;
		XLSFileKit xlsFileKit = new XLSFileKit(filePath);
		List<List<Object>> content = new ArrayList<List<Object>>();
		List<String> title = new ArrayList<String>();
		
		List<Record> datas = exportExcelService.getList();
		
		// 添加`title`,對應的從數據庫檢索出`datas`的`title`
		
		title.add("序號");
		title.add("id");
		title.add("caseId");
		title.add("imgId");
		int i = 0;
		OK:
		while(true){
			if(datas.size() < (i + 1)){
				break OK;
			}
			// 判斷單元格是否為空,不為空添加數據 
			int index = i + 1;
			List<Object> row = new ArrayList<Object>(); 
			row.add(index + "");
			row.add(null==datas.get(i).get("id")?"":datas.get(i).get("id"));
			row.add(null==datas.get(i).get("caseId")?"":datas.get(i).get("caseId"));
			row.add(null==datas.get(i).get("imgId")?"":datas.get(i).get("imgId"));
			content.add(row);
			i ++;
		}
		xlsFileKit.addSheet(content, sheetName, title);
		xlsFileKit.save();
		renderJson(new Record().set("relativePath", relativePath));
	}
	
}



對應的Service類,ExportExcelService


package service;

import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class ExportExcelService {

	public List<Record> getList(){
		
		String sql = "select * from zt_case_img";
		
		return Db.find(sql);
	}
	
}


然后再頁面上添加一個按鈕調用這個方法即可,另還要在config中配置路由。


		me.add("/excel", ExportExcelController.class);

調用方法:


$("#export").click(function(){
    	
    	$.post("excel/exportOutExcel",{sheetName:"報表"},function(data){
    		
    		var relativePath = data.relativePath;
			window.location.href = ".." + relativePath;
    		
    	});
    });

調用成功后會自動在webRoot/file/export/下生成一個你導出的excel.

項目目錄結構:

outPut

導出成功:

outPut

部分源代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM