在mymes管理系統中,人員管理,訂單等操做須要報表的導入導出等邏輯。需求看是複雜,實際上就是對數據庫表的基本操做,本文介紹Excel的導出,下次介紹數據的導入java
在企業應用開發中,Excel報表是一種最多見的報表需求。Excel報表開發通常有兩種方式:git
目前Excel存在兩個版本Excel2003和Excel2007以上的版本,二者之間區別:github
Java中常見的EXCEL操做方式有兩種:jxl和poi。數據庫
<!--POI Excel--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>4.0.1</version> </dependency>
HPBF提供讀Publisher格式文檔apache
public class PoiTest01 { //測試建立excel文件 public static void main(String[] args) throws Exception { //1.建立workbook工做簿 Workbook wb = new XSSFWorkbook(); //2.建立表單Sheet Sheet sheet = wb.createSheet("test"); //3.文件流 FileOutputStream fos = new FileOutputStream("E:\\test.xlsx"); //4.寫入文件 wb.write(fos); fos.close(); } }
//測試建立單元格 public static void main(String[] args) throws Exception { //1.建立workbook工做簿 Workbook wb = new XSSFWorkbook(); //2.建立表單Sheet Sheet sheet = wb.createSheet("test"); //3.建立行對象,從0開始 Row row = sheet.createRow(3); //4.建立單元格,從0開始 Cell cell = row.createCell(0); //5.單元格寫入數據 cell.setCellValue("傳智播客"); //6.文件流 FileOutputStream fos = new FileOutputStream("E:\\test.xlsx"); //7.寫入文件 wb.write(fos); fos.close(); }
//建立單元格樣式對象 CellStyle cellStyle = wb.createCellStyle(); //設置邊框 cellStyle.setBorderBottom(BorderStyle.DASH_DOT);//下邊框 cellStyle.setBorderTop(BorderStyle.HAIR);//上邊框 //設置字體 Font font = wb.createFont();//建立字體對象 font.setFontName("華文行楷");//設置字體 font.setFontHeightInPoints((short)28);//設置字號 cellStyle.setFont(font); //設置寬高 sheet.setColumnWidth(0, 31 * 256);//設置第一列的寬度是31個字符寬度 row.setHeightInPoints(50);//設置行的高度是50個點 //設置居中顯示 cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中 //設置單元格樣式 cell.setCellStyle(cellStyle); //合併單元格 CellRangeAddress region =new CellRangeAddress(0, 3, 0, 2); sheet.addMergedRegion(region);
//繪製圖形 public static void main(String[] args) throws Exception { //1.建立workbook工做簿 Workbook wb = new XSSFWorkbook(); //2.建立表單Sheet Sheet sheet = wb.createSheet("test"); //讀取圖片流 FileInputStream stream=new FileInputStream("e:\\logo.jpg"); byte[] bytes= IOUtils.toByteArray(stream); //讀取圖片到二進制數組 stream.read(bytes); //向Excel添加一張圖片,並返回該圖片在Excel中的圖片集合中的下標 int pictureIdx = wb.addPicture(bytes,Workbook.PICTURE_TYPE_JPEG); //繪圖工具類 CreationHelper helper = wb.getCreationHelper(); //建立一個繪圖對象 Drawing<?> patriarch = sheet.createDrawingPatriarch(); //建立錨點,設置圖片座標 ClientAnchor anchor = helper.createClientAnchor(); anchor.setCol1(0);//從0開始 anchor.setRow1(0);//從0開始 //建立圖片 Picture picture = patriarch.createPicture(anchor, pictureIdx); picture.resize(); //6.文件流 FileOutputStream fos = new FileOutputStream("E:\\test.xlsx"); //7.寫入文件 wb.write(fos); fos.close(); }
不管是什麼需求只有有報表的導出就須要一下步驟:數組
package com.cn.greemes.common.util; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.IdUtil; import cn.hutool.poi.excel.BigExcelWriter; import cn.hutool.poi.excel.ExcelUtil; import org.apache.poi.xssf.streaming.SXSSFSheet; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; /** * 文件操做 */ public class FileUtil { public static final String SYS_TEM_DIR =System.getProperty("java.io.tmpdir")+ File.separator; public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException { String tempPath = SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".xlsx"; File file = new File(tempPath); BigExcelWriter writer = ExcelUtil.getBigWriter(file); // 一次性寫出內容,使用默認樣式,強制輸出標題 writer.write(list, true); SXSSFSheet sheet = (SXSSFSheet)writer.getSheet(); //上面須要強轉SXSSFSheet 否則沒有trackAllColumnsForAutoSizing方法 sheet.trackAllColumnsForAutoSizing(); //列寬自適應 writer.autoSizeColumnAll(); //response爲HttpServletResponse對象 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); //test.xls是彈出下載對話框的文件名,不能爲中文,中文請自行編碼 response.setHeader("Content-Disposition", "attachment;filename=file.xlsx"); ServletOutputStream out = response.getOutputStream(); // 終止後刪除臨時文件 file.deleteOnExit(); writer.flush(out, true); //此處記得關閉輸出Servlet流 IoUtil.close(out); } }
@ApiOperation("導出用戶數據") @RequestMapping(value = "/export", method = RequestMethod.GET) @ResponseBody public void export(HttpServletResponse response, @RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) throws UnsupportedEncodingException, IOException { Page<MesAdmin> adminList = adminService.list(keyword, pageSize, pageNum); List<Map<String,Object>> list = new ArrayList(); for(int i=0;i<149;i++) { for (MesAdmin umsAdmin : adminList.getRecords()) { Map<String, Object> map = new LinkedHashMap<>(6); map.put("姓名", umsAdmin.getUsername()); map.put("郵箱", umsAdmin.getEmail()); map.put("暱稱", umsAdmin.getNickName()); map.put("備註信息", umsAdmin.getNote()); map.put("建立時間", umsAdmin.getCreateTime()); map.put("最後登陸時間", umsAdmin.getLoginTime()); list.add(map); } } fileUtil.downloadExcel(list,response); }
這次介紹的是Excel的導出,下次介紹Excel的導入,這是我在工做時的一點總結,有什麼不對的請多直接,共同進步,謝謝!app
github地址:https://github.com/bangbangzhou/greemes/tree/masterxss