最近做grid列表相關數據導出到excel功能,根據自己選擇的列導出成excel 並且下載到本地。廢話不說 直接上關鍵代碼:
需要引入相關的包:
compile 'org.apache.poi:poi-ooxml:3.9'
compile 'org.apache.poi:poi:3.9'
compile 'org.apache.poi:poi-scratchpad:3.9'
這是我項目中gradle的配置。
1.js 代碼
window.location.href="export/exportExcel?ids=" + this.selectedId; // 此處的selectedId 就是單選或者多選多列的id集合
2. controller
import com.fndsoft.bcis.model.WithdrawDeposit;
import com.fndsoft.bcis.service.SettlementService;
import com.fndsoft.bcis.utils.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by bai on 2016/7/26.
*/
@Controller
@RequestMapping(value = "/export")
public class ExportExcelController {
@Autowired
private SettlementService settlementService;
/**
* 根據多選的結算申請導出excel
*
* @return
*/
@RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> exportExcel(@RequestParam Integer[] ids, HttpServletResponse response) throws IOException {
String fileName = new Date().getTime() + ".xls";
//填充projects數據
List<WithdrawDeposit> projects = createData(ids);
List<Map<String, Object>> list = createExcelRecord(projects);
String columnNames[] = {"申請號", "提現金額", "申請時間", "支付類型", "賬號", "狀態"};//列名
String keys[] = {"applicationNo", "amount", "opTime", "payType", "accountNo", "status"};//map中的key
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
} catch (IOException e) {
e.printStackTrace();
}
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
// 設置response參數,可以打開下載頁面
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes(), "iso-8859-1"));
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
// Simple read/write loop.
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (final IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return null;
}
private List<WithdrawDeposit> createData(Integer[] ids) {
//自己實現
return null;
}
private List<Map<String, Object>> createExcelRecord(List<WithdrawDeposit> projects) {
List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
map.put("sheetName", "sheet1");
listmap.add(map);
WithdrawDeposit project;
for (int j = 0; j < projects.size(); j++) {
project = projects.get(j);
Map<String, Object> mapValue = new HashMap<>();
mapValue.put("applicationNo", project.getApplicationNo());
mapValue.put("amount", project.getAmount());
mapValue.put("opTime", format.format(project.getOpTime()));
mapValue.put("payType", project.getPayType());
mapValue.put("accountNo", project.getAccountNo());
mapValue.put("status", project.getStatus());
listmap.add(mapValue);
}
return listmap;
}
}
3.excel導出幫助類
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
/**
* 導出Excel文檔工具類
*
* @author bai
* @date 2016-7-25
*/
public class ExcelUtil {
/**
* 創建excel文檔,
*
* @param list 數據
* @param keys list中map的key數組集合
* @param columnNames excel的列名
*/
public static Workbook createWorkBook(List<Map<String, Object>> list, String[] keys, String columnNames[]) {
// 創建excel工作簿
Workbook wb = new HSSFWorkbook();
// 創建第一個sheet(頁),並命名
Sheet sheet = wb.createSheet(list.get(0).get("sheetName").toString());
// 手動設置列寬。第一個參數表示要為第幾列設;,第二個參數表示列的寬度,n為列高的像素數。
for (int i = 0; i < keys.length; i++) {
sheet.setColumnWidth((short) i, (short) (35.7 * 150));
}
// 創建第一行
Row row = sheet.createRow((short) 0);
// 創建兩種單元格格式
CellStyle cs = wb.createCellStyle();
CellStyle cs2 = wb.createCellStyle();
// 創建兩種字體
Font f = wb.createFont();
Font f2 = wb.createFont();
// 創建第一種字體樣式(用於列名)
f.setFontHeightInPoints((short) 10);
f.setColor(IndexedColors.BLACK.getIndex());
f.setBoldweight(Font.BOLDWEIGHT_BOLD);
// 創建第二種字體樣式(用於值)
f2.setFontHeightInPoints((short) 10);
f2.setColor(IndexedColors.BLACK.getIndex());
// 設置第一種單元格的樣式(用於列名)
cs.setFont(f);
cs.setBorderLeft(CellStyle.BORDER_THIN);
cs.setBorderRight(CellStyle.BORDER_THIN);
cs.setBorderTop(CellStyle.BORDER_THIN);
cs.setBorderBottom(CellStyle.BORDER_THIN);
cs.setAlignment(CellStyle.ALIGN_CENTER);
// 設置第二種單元格的樣式(用於值)
cs2.setFont(f2);
cs2.setBorderLeft(CellStyle.BORDER_THIN);
cs2.setBorderRight(CellStyle.BORDER_THIN);
cs2.setBorderTop(CellStyle.BORDER_THIN);
cs2.setBorderBottom(CellStyle.BORDER_THIN);
cs2.setAlignment(CellStyle.ALIGN_CENTER);
//設置列名
for (int i = 0; i < columnNames.length; i++) {
Cell cell = row.createCell(i);
cell.setCellValue(columnNames[i]);
cell.setCellStyle(cs);
}
//設置每行每列的值
for (short i = 1; i < list.size(); i++) {
// Row 行,Cell 方格 , Row 和 Cell 都是從0開始計數的
// 創建一行,在頁sheet上
Row row1 = sheet.createRow(i);
// 在row行上創建一個方格
for (short j = 0; j < keys.length; j++) {
Cell cell = row1.createCell(j);
cell.setCellValue(list.get(i).get(keys[j]) == null ? " " : list.get(i).get(keys[j]).toString());
cell.setCellStyle(cs2);
}
}
return wb;
}
}
執行之后會在你瀏覽器的下邊看到下載的文件直接雙擊打開就行。
