java:匯出excel,瀏覽器下載
阿新 • • 發佈:2018-12-16
ExcelUtil類
import com.xjl.student.model.Person; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Excel匯出 */ public class ExcelUtil { /** * 匯出excel檔案 */ public HSSFWorkbook exprotExcel(List<Person> list, String headInfo, String filepath){ // 第一步、建立一個workbook物件,對應一個Excel檔案 HSSFWorkbook wb = new HSSFWorkbook(); // 第二步、在workbook中新增一個sheet,對應Excel檔案中的sheet HSSFSheet sheet = wb.createSheet("sheet_1"); sheet.setDefaultColumnWidth(20); sheet.setDefaultRowHeight((short) 30); sheet.setHorizontallyCenter(true); //上下左右內邊距 sheet.setMargin(HSSFSheet.BottomMargin, (double)1.0); sheet.setMargin(HSSFSheet.LeftMargin, (double)0.7); sheet.setMargin(HSSFSheet.RightMargin, (double)0.7); sheet.setMargin(HSSFSheet.TopMargin, (double)1.0); // 第三步,在sheet中新增表頭第0行需合併單元格 CellRangeAddress region = new CellRangeAddress(0,0,0,3); sheet.addMergedRegion(region); HSSFRow row0 = sheet.createRow((int) 0); // 在sheet中新增表頭第1行 HSSFRow row = sheet.createRow((int) 1); row0.setHeightInPoints((float) 18); row.setHeightInPoints((float) 18); // 第四步,建立單元格,並設定值表頭 設定表頭居中 HSSFCellStyle style = wb.createCellStyle(); //設定居中格式--水平居中且垂直居中 style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION); HSSFFont font = wb.createFont(); //設定字型,9號加粗 font.setFontHeightInPoints((short) 12); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); style.setFont(font); //設定表頭行各個列的名字 setSheetHeader0(row0, style, headInfo); setSheetHeader(row, style); //第五步,新增匯出資料到表中 insertDatasToSheet(sheet, list); //第六步,將excel檔案存到指定位置 // writeExcelToDisk(filepath, wb); return wb; } /** * 將excel檔案存到指定位置 * @param filePath * @param wb */ private void writeExcelToDisk(String filePath, HSSFWorkbook wb) { try { FileOutputStream fos = new FileOutputStream(filePath); wb.write(fos); fos.close(); System.out.println("excel已經匯出到:" + filePath); } catch (Exception e) { e.printStackTrace(); } } /** * 新增匯出資料到表中 * @param sheet * @param list */ private void insertDatasToSheet(HSSFSheet sheet, List<Person> list) { HSSFCell cell = null; HSSFRow row = null; for (int i = 0; i < list.size(); i++) { row = sheet.createRow((int) i + 2); Person person = list.get(i); // 建立單元格,並設定各個列中實際資料的值 cell = row.createCell(0); cell.setCellValue(i+1); cell = row.createCell(1); cell.setCellValue(person.getId()); cell = row.createCell(2); cell.setCellValue(person.getName()); cell = row.createCell(3); cell.setCellValue(person.getAge()); } } /** * 設定表頭行各個列的名字 * @param row * @param style */ private void setSheetHeader0(HSSFRow row, HSSFCellStyle style, String headInfo) { HSSFCell cell = row.createCell(0); cell.setCellStyle(style); cell.setCellValue(headInfo); cell = row.createCell(1); } private void setSheetHeader(HSSFRow row, HSSFCellStyle style) { HSSFCell cell = row.createCell(0); cell.setCellStyle(style); cell.setCellValue("序號"); cell = row.createCell(1); cell.setCellStyle(style); cell.setCellValue("學號"); cell = row.createCell(2); cell.setCellStyle(style); cell.setCellValue("姓名"); cell = row.createCell(3); cell.setCellStyle(style); cell.setCellValue("年齡"); } /** * 創造資料 * @return */ private static List<Person> getStudentData() { List<Person> list = new ArrayList<Person>(); for (int i = 1; i <= 3; i++) { Person stu = new Person(i, "學生_" + i, 10 + i); list.add(stu); } return list; } public static void main(String[] args){ ExcelUtil excelUtil = new ExcelUtil(); String dateTime = DateFormatUtils.format(new Date(), "yyMMdd_HHmmss"); String filepath = "D:/app/ExportExcel_" + dateTime + ".xls"; List<Person> list = ExcelUtil.getStudentData(); excelUtil.exprotExcel(list,"匯出excel檔案"+dateTime, filepath); } }
Person類
import lombok.Data;
@Data
public class Person {
private int id;
private String name;
private int age;
}
瀏覽器下載所需程式碼
import com.xjl.student.model.Person; import com.xjl.student.util.ExcelUtil; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; 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.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; import java.util.*; /** * exportExcel * http://localhost:10086/exportCase/exportExcel */ @RestController @RequestMapping("/exportCase") public class ExportExcelController { @RequestMapping(value = "exportExcel",method = RequestMethod.GET) public void exportExcel(HttpServletResponse response) { String dateTime = DateFormatUtils.format(new Date(), "yyMMdd_HHmmss"); String filepath = "D:/app/ExportExcel_" + dateTime + ".xls"; ExcelUtil excelUtil = new ExcelUtil(); List<Person> list = getData(); //建立excel HSSFWorkbook workbook = excelUtil.exprotExcel(list,"TestExportExcel"+dateTime, filepath); OutputStream output = null; try { output = response.getOutputStream(); //清空快取 response.reset(); // 定義瀏覽器響應表頭,並定義下載名 String fileName = URLEncoder.encode("ExportExcel_"+dateTime+".xls", "UTF-8"); response.setHeader("Content-disposition", "attachment;filename="+fileName); //定義下載的型別,標明是excel檔案 response.setContentType("application/vnd.ms-excel;charset=UTF-8"); //把建立好的excel寫入到輸出流 workbook.write(output); //隨手關門 output.close(); }catch (IOException e){ e.printStackTrace(); } } private static List<Person> getData() { List<Person> list = new ArrayList<Person>(); for (int i = 1; i <= 3; i++) { Person stu = new Person(); stu.setId(i); stu.setName("學生_"+i); stu.setAge(10+i); list.add(stu); } return list; } }
注:
(1)pom:poi.3.7
(2)Excel Util類中,第六步選擇執行則會將檔案單獨在本地磁碟備份一份
(3)上述程式碼未用到資料庫,但可自行查詢資料再放入list中即可
(4)瀏覽器下載地址IP、埠自行查詢
(5)效果圖如下: