1. 程式人生 > >Java中用poi技術將報表匯出成excel表

Java中用poi技術將報表匯出成excel表

    我相信有很多程式猿都像小M一樣遇到過需要將報表匯出成excel表的情況,看了網上的demo還是有點蒙的人,看過來,在這裡由小M系統的給大家講解一下。

    在這裡,小M用的技術是poi技術,框架是springBoot+Maven,有需要的參考下

(1)、首先,先引入maven所需的依賴包,我這裡用的是3.16版本

<dependency>
    	<groupId>org.apache.poi</groupId>
    	<artifactId>poi</artifactId>    
    	<version>3.16</version>	
</dependency> 
(2)、引入建立excel表的工具類GradesXLS
package com.xx.test.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

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;

/**
 * 
 * 匯出XLS檔案
 *
 */
public class GradesXLS {

	private String path;

	public GradesXLS() {
		super();
	}
	
	//建構函式獲取儲存excel路徑
	public GradesXLS(String path) {
		super();
		this.path = path;
	}
	
	public Boolean CreateExcel(List<Object[]> dataList, String[] column, String clientName, HttpServletResponse response) throws Exception {
		//建立一個工作簿
		HSSFWorkbook workBook = new HSSFWorkbook();
		//建立一個工作表,名為:第一頁
		HSSFSheet sheet = workBook.createSheet(clientName);
		//設定單元格的寬度(0:表示第一行的第一個單元格,1:第一行的第二個單元格)
		sheet.setColumnWidth((short) 0, 3500);
		sheet.setColumnWidth((short) 1, 5000);
		sheet.setColumnWidth((short) 2, 5000);
		//建立一個單元格,從0開始
		HSSFRow row = sheet.createRow((short) 0);
		//構造一個數組設定第一行之後的單元格
		HSSFCell[] cell = new HSSFCell[column.length];
		for (int i = 0; i < column.length; i++) {
			cell[i] = row.createCell(i);
			cell[i].setCellValue(column[i]);
		}
		
		//獲得從資料庫中查詢出來的資料
		if (dataList != null && dataList.size() > 0) {
			//迴圈list中的資料
			for (int i = 0; i < dataList.size(); i++) {
				Object[] objs = dataList.get(i);
				HSSFRow dataRow = sheet.createRow(i + 1);
				HSSFCell data[] = new HSSFCell[column.length];
				for (int j = 0; j < column.length; j++) {
					data[j] = dataRow.createCell(j);
					String info = String.valueOf(objs[j]);
					System.out.println("GradesXLS:" + info);
					data[j].setCellValue((info == null) ? "" : info);
				}
			 }
			
			try {
//				String fileName = clientName + "-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
				//設定日期格式
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				// new Date()為獲取當前系統時間,也可使用當前時間戳
				String date = df.format(new Date());
				String fileName = clientName + "-" + date + ".xls";//檔名,客戶端名+日期+檔案字尾名
				response.setContentType("application/vnd.ms-excel");//設定內容格式
				response.setCharacterEncoding("utf-8");//設定編碼格式
				response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("gbk"), "iso8859-1"));
				//用IO流來寫進去
				OutputStream os = response.getOutputStream();
				workBook.write(os);
				os.flush();
				return true;
			} catch (FileNotFoundException e) {
				// TODO: handle exception
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				// TODO: handle exception
				e.printStackTrace();
				return false;
			}
		} 
		return false;
	}
	
}
(3)、controller類
	@Autowired
	private SubjectService subjectService;

	/**
	 * 成績單
	 */
	
	@RequestMapping(value="/subjectList")
	@ResponseBody
	public Object getSubjectList()  {
		
		return subjectService.getSubjectList();
		
	}

(4)、最重要的service層來了

//成績單
	@Autowired
	private SubjectDao subjectDao;
//方法
public Object subjectExcel(HttpServletResponse response) {
		String[] column = {"學號","語文","數學","英語","體育"};
		String clientName = "成績單";
	
		//資料組裝
		ArrayList<Object[]> dataList = new ArrayList<>();
		List<SubjectOut> subjectList = subjectDao.subjectExcel(SubjectOut.class);//查詢資料庫表,將結果放入SubjectOut類中返回
		//判斷查出來的資料是否為空
		if (subjectList != null && subjectList.size() > 0) {
			GradesXLS xls = new GradesXLS();//例項化剛才的工具類   //迴圈新增資料
			for (SubjectOut subjectInfo : subjectList) {
				Object[] obj = {subjectInfo.getId(),subjectInfo.getChinese(),subjectInfo.getMath(),subjectInfo.getSports()};
				dataList.add(obj);
			}
			try {
				return xls.CreateExcel(dataList,column,clientName,response);//將工具類創建出的excel返會下載
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

(5)、dao層就自己寫吧,這個比較簡單

(6)、懶得寫資料表的話,我給大家貼出來一個

CREATE TABLE `tb_subject` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `chinese` varchar(255) DEFAULT NULL,
  `math` varchar(255) DEFAULT NULL,
  `english` varchar(255) DEFAULT NULL,
  `sports` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_subject
-- ----------------------------
INSERT INTO `tb_subject` VALUES ('1', '98', '100', '87', '90');
INSERT INTO `tb_subject` VALUES ('2', '88', '98', '86', '100');
INSERT INTO `tb_subject` VALUES ('3', '84', '85', '86', '87');
INSERT INTO `tb_subject` VALUES ('4', '91', '92', '93', '94');
INSERT INTO `tb_subject` VALUES ('5', '84', '87', '89', '97');
INSERT INTO `tb_subject` VALUES ('6', '91', '94', '95', '92');
INSERT INTO `tb_subject` VALUES ('7', '94', '92', '97', '91');
INSERT INTO `tb_subject` VALUES ('8', '75', '78', '79', '90');
INSERT INTO `tb_subject` VALUES ('9', '84', '72', '73', '91');
INSERT INTO `tb_subject` VALUES ('10', '85', '81', '72', '73');

好了,分享到此結束,有問題在下面留言呀,小M為您解答,謝謝大家,覺得好的贊一個,,muma