在實際開發中我們經常需要導入數據,統計數據,並且將統計好的數據導出excel,今天分享一個導出學生信息的方法。
目前,比較常用的實現Java導入、導出Excel的技術有兩種Jakarta POI和Java Excel。
Jakarta POI 是一套用於訪問微軟格式文檔的Java API。Jakarta POI有很多組件組成,其中有用於操作Excel格式文件的HSSF和用於操作Word的HWPF,目前用於操作Excel的HSSF比較成熟。官方主頁,API文檔
使用步驟:
一:下載jar包,並放在工程的WEB-INF——>lib目錄下
下載地址:http://poi.apache.org/download.html
目前最新版本是4.0,我使用的是3.9
二:理解HSSFWorkbook的幾種對象:
HSSFWorkbook:excel的工作簿
HSSFSheet:excel的工作表
HSSFRow:excel的行
HSSFCell:excel的單元格
HSSFFont:excel字體
HSSFDataFormat:日期格式
HSSFHeader:sheet頭
樣式:
HSSFCellStyle:單元格樣式
一個Excel的文件對應一個工作簿(HSSFWorkbook),一個工作簿可以有多個工作表(我們通常看到的Sheet0、Sheet1)(HSSFSheet)組成,一個工作表是由多行(HSSFRow)組成,一行又是由多個單元格(HSSFCell)組成。
三:定義導出數據的請求接口,一般的業務邏輯在這裏處理
/**
* 導出學生信息
* @param request
* @param response
* @throws IOException
*/
@RequestMapping("/studentInfoExcelOut")
public void studentInfoExcelOut(HttpServletRequest request, HttpServletResponse response)
throws IOException {
/**獲取導出數據,實際開發中這裏一般是從數據庫查詢的數據,
這裏演示是定義了一個實體對象,然後初始化多個對象,並放進我們需要導出的集合裏*/
List<Student> list = new ArrayList<>();
int sex = 1;
for(int i = 0 ;i < 10 ;i++){
if(i%2 == 0){
sex = 2;
}
Student stu = new Student(i+1,"學生"+(i+1)+"號",sex,18+i,20190001+i,"1998年-"+(i+1)+"月",new Date());
list.add(stu);
}
exportExcelBook(request,response,list);
return;
}
由於我們是導出學生的基礎信息,所以需要定義一個學生實體類對象Student.java:
public class Student {
/**學生id*/
private int id;
/**學生姓名*/
private String name;
/**學生性別 1:男 2:女*/
private int sex;
/**學生年齡*/
private int age;
/**學生學號*/
private int student_no;
/**學生出生年月*/
private String birthday;
/**學生創建時間*/
private Date create_time;
public Student(int id,String name,int sex,int age,int student_no,String birthday,Date create_time) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
this.student_no = student_no;
this.birthday = birthday;
this.create_time = create_time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getStudent_no() {
return student_no;
}
public void setStudent_no(int student_no) {
this.student_no = student_no;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
}
四:調用HSSFWorkbook提供的方法將所需要導出的數據導出並生成文件
/**
* 導出數據生成EXCEL方法
* @param request
* @param response
* @param list
* @throws IOException
*/
public void exportExcelBook(HttpServletRequest request, HttpServletResponse response,List<Student> list)
throws IOException {
if (CollectionUtils.isEmpty(list)) {
return;
}
//文件名稱,客戶端傳來的參數,防止中文文件名亂碼參數編碼因此這裏需要解碼
String fileName = URLDecoder.decode(request.getParameter("fileName"),"UTF-8");
//創建Excel工作薄對象
HSSFWorkbook workbook = new HSSFWorkbook();
//創建Excel工作表對象
HSSFSheet sheet = workbook.createSheet();
sheet.setColumnWidth(0, 3000);
sheet.setColumnWidth(1, 5000);
sheet.setColumnWidth(2, 4000);
sheet.setColumnWidth(3, 2500);
sheet.setColumnWidth(4, 3000);
sheet.setColumnWidth(5, 6000);
sheet.setColumnWidth(6, 6000);
// 設置表頭字體樣式
HSSFFont columnHeadFont = workbook.createFont();
columnHeadFont.setFontName("宋體");
columnHeadFont.setFontHeightInPoints((short) 10);
columnHeadFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 列頭的樣式
HSSFCellStyle columnHeadStyle = workbook.createCellStyle();
columnHeadStyle.setFont(columnHeadFont);
// 左右居中
columnHeadStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 上下居中
columnHeadStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
columnHeadStyle.setLocked(true);
columnHeadStyle.setWrapText(true);
// 左邊框的顏色
columnHeadStyle.setLeftBorderColor(HSSFColor.BLACK.index);
// 邊框的大小
columnHeadStyle.setBorderLeft((short) 1);
// 右邊框的顏色
columnHeadStyle.setRightBorderColor(HSSFColor.BLACK.index);
// 邊框的大小
columnHeadStyle.setBorderRight((short) 1);
// 設置單元格的邊框爲粗體
columnHeadStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
// 設置單元格的邊框顏色
columnHeadStyle.setBottomBorderColor(HSSFColor.BLACK.index);
// 設置單元格的背景顏色(單元格的樣式會覆蓋列或行的樣式)
columnHeadStyle.setFillForegroundColor(HSSFColor.WHITE.index);
// 設置普通單元格字體樣式
HSSFFont font = workbook.createFont();
font.setFontName("宋體");
font.setFontHeightInPoints((short) 10);
//創建Excel工作表第一行
HSSFRow row0 = sheet.createRow(0);
// 設置行高
row0.setHeight((short) 750);
HSSFCell cell = row0.createCell(0);
//設置單元格內容
cell.setCellValue(new HSSFRichTextString("學生id"));
//設置單元格字體樣式
cell.setCellStyle(columnHeadStyle);
cell = row0.createCell(1);
cell.setCellValue(new HSSFRichTextString("姓名"));
cell.setCellStyle(columnHeadStyle);
cell = row0.createCell(2);
cell.setCellValue(new HSSFRichTextString("性別"));
cell.setCellStyle(columnHeadStyle);
cell = row0.createCell(3);
cell.setCellValue(new HSSFRichTextString("年齡"));
cell.setCellStyle(columnHeadStyle);
cell = row0.createCell(4);
cell.setCellValue(new HSSFRichTextString("學號"));
cell.setCellStyle(columnHeadStyle);
cell = row0.createCell(5);
cell.setCellValue(new HSSFRichTextString("出生年月"));
cell.setCellStyle(columnHeadStyle);
cell = row0.createCell(6);
cell.setCellValue(new HSSFRichTextString("創建時間"));
cell.setCellStyle(columnHeadStyle);
// 循環寫入數據
for (int i = 0; i < list.size(); i++) {
Student stu = list.get(i);
HSSFRow row = sheet.createRow(i + 1);
cell = row.createCell(0);
cell.setCellValue(new HSSFRichTextString(String.valueOf(stu.getId())));
cell.setCellStyle(columnHeadStyle);
cell = row.createCell(1);
cell.setCellValue(new HSSFRichTextString(stu.getName()));
cell.setCellStyle(columnHeadStyle);
cell = row.createCell(2);
if(stu.getSex() == 1){
cell.setCellValue(new HSSFRichTextString("男"));
}else{
cell.setCellValue(new HSSFRichTextString("女"));
}
cell.setCellStyle(columnHeadStyle);
cell = row.createCell(3);
cell.setCellValue(new HSSFRichTextString(String.valueOf(stu.getAge())));
cell.setCellStyle(columnHeadStyle);
cell = row.createCell(4);
cell.setCellValue(new HSSFRichTextString(String.valueOf(stu.getStudent_no())));
cell.setCellStyle(columnHeadStyle);
cell = row.createCell(5);
cell.setCellValue(new HSSFRichTextString(stu.getBirthday()));
cell.setCellStyle(columnHeadStyle);
cell = row.createCell(6);
cell.setCellValue(new HSSFRichTextString());
cell.setCellStyle(columnHeadStyle);
cell.setCellValue(new HSSFRichTextString(DateUtils.DateToString(stu.getCreate_time(), "yyyy-MM-dd HH:mm:ss")));
}
// 獲取輸出流
OutputStream os = response.getOutputStream();
// 重置輸出流
response.reset();
// 設定輸出文件頭
response.setHeader("Content-disposition",
"attachment; filename=" + new String(fileName.getBytes("GB2312"), "8859_1") + ".xls");
// 定義輸出類型
response.setContentType("application/msexcel");
workbook.write(os);
os.close();
return;
}
五:網頁調用導出excel接口
<a href="javascript:void(0)" οnclick="outExcel()">導出學生信息</a>
<script>
function outExcel(){
var fileName ="學生信息表";
//編碼防止中文字符亂碼
window.location.href=encodeURI("studentInfoExcelOut?fileName="+encodeURIComponent(fileName));
}
</script>
六:導出excel截圖:
版權聲明:本文爲CSDN博主「caicai1171523597」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/caicai1171523597/article/details/86643667