Introduction: in the actual development often need to export data from the database into excel file, poi one embodiment is more commonly derived framework. Simple to read excel file in the previous one has explained
The project implementation requirements: user issues a request to export student information, download excel file containing all student information to the machine. Just put the key code , not put up is very simple, self-brain supplement
Overall process (the server): receiving a request ------> ------ extracted database data> data is saved as a temporary file excel ------> allows the browser in response to the first temporary file download ------> delete temporary files
Project structure:
1. Import dependence
<!--poi--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency>
2.controller
package com.zjk.excel.controller; import com.zjk.excel.service.UserServiceI; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; import java.io.*; /** * @Auther: zjk * @Date: 2019/9/16 * @Description: */ @Controller @RequestMapping("/user") public class UserController { @Autowired UserServiceI UserServiceI; @ RequestMapping ( "/ Export" ) public void exportStu (HttpServletResponse the Response) { // set the default download filename String name = "Student Information table .xlsx" ; the try { // avoid Chinese file name garbled, the UTF8 recombined break ISO-8859-1 encoding name = new new String (name.getBytes ( "the UTF8"), "ISO-8859-1" ); } the catch (UnsupportedEncodingException E) { e.printStackTrace (); } // type response header set the response.setContentType ( "file application / vnd.openxmlformats-officedocument.spreadsheetml.sheet" ); // let the browser download the file, name is above the default file name to download response.addHeader ( "Content-Disposition", "attachment; filename = \ "" + name + "\" " ); InputStream inputStream = null ; OutputStream outputStream = null ; // has become excel data is stored in a temporary file service layer, and return to the path of the temporary file String DownloadPath = userServiceI.exportStu (); // create file objects based on the path for temporary files, you need to use FileInputStream read file file = new new file (DownloadPath); try { // by FileInputStream read the temporary file, ServletOutputStream written to the temporary file browser inputStream = new new FileInputStream (file); the outputStream = response.getOutputStream (); int len = -1 ; byte [] B = new new byte [1024 ]; the while ((len = inputStream .read (B)) = -1! ) { OutputStream.write (B); } // refresh outputStream.flush (); } the catch (Exception E) { e.printStackTrace (); } the finally { // Close the input and output streams the try { IF (inputStream =! Null {) inputStream.close (); } } the catch (IOException E) { e.printStackTrace (); } the try { IF (! The outputStream = null ) { outputStream.close (); } } the catch (IOException E) { e.printStackTrace (); } } // Finally to delete the temporary file if the use of a temporary file stream, File.delete () is not deleted File.delete (); } }
3.service
package com.zjk.excel.service.impl; import com.zjk.excel.dao.StudentDao; import com.zjk.excel.dao.UserDao; import com.zjk.excel.entity.Student; import com.zjk.excel.service.UserServiceI; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.*; importjava.util.List; Import java.util.UUID; / ** * @Auther: ZJK * @date: 2019/9/16 * @Description: * / @Service public class UserService the implements UserServiceI { // create a temporary file storage path Private String TEMP = "D: \\ TEMP \\ \\ Excel" ; @Autowired UserDao userDao; @Autowired StudentDAO StudentDAO; @Override public String exportStu () { List <Student> List = studentDao.queryAllStu (); / / create workbooks xSSFWorkbook xssfWorkbook =new new XSSFWorkbook (); // Create a worksheet XSSFSheet Sheet = xssfWorkbook.createSheet (); xssfWorkbook.setSheetName ( 0, "Student Information Form" ); // Create a header XSSFRow head = sheet.createRow (0 ); String [] Heads = { "No. "," name "," age "," sex "," phone number " }; for ( int I = 0; I <. 5; I ++ ) { XSSFCell Cell = head.createCell (I); cell.setCellValue (Heads [ I]); } for ( int I =. 1; I <=. 4; I ++ ) { Student student = List.get (I -. 1 ); // create a row, starting from the second row, so that the for loop i from 1 starts taking XSSFRow Row = sheet.createRow (i); // create a cell and padding data XSSFCell cell = row.createCell (0 ); cell.setCellValue (student.getS_id ()); Cell = row.createCell (. 1 ); cell.setCellValue (student.getS_name ()); Cell = row.createCell (2 ); cell.setCellValue (student.getS_age ()); the Cell = row.createCell (3 ); cell.setCellValue ( "male" .equals (student.getS_gender () trim ( )) " man":? "female" ); the Cell = row.createCell (4 a FileOutputStream (DownloadPath); ); cell.setCellValue (student.getS_tel ()); } // create temporary files directory File File = new new File (the TEMP); IF (! {File.Exists ()) file.mkdirs (); } // temporary file path / file name String file + DownloadPath = "\\" + System.currentTimeMillis () + UUID.randomUUID (); the OutputStream the outputStream = null ; the try {
data in memory will be written to the local FileOutputStream // use, generates a temporary file the outputStream = new new xssfWorkbook.write (the outputStream); outputStream.flush (); } catch (Exception e) { e.printStackTrace(); } finally { try { if(outputStream != null) { outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return downloadPath; } }
4. Effects
After the WPS Open: can be said to be very ugly, then optimize it
Increases in service in the following code: Overall still very troublesome, create CellStyle, but also you want to change the style of the cell were cell.setCellStyle (style1) can
* Bo master version is relatively new, so there are many places older version differences
//创建styleHead CellStyle styleHead = xssfWorkbook.createCellStyle(); styleHead.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());//背景色 styleHead.setFillPattern(FillPatternType.SOLID_FOREGROUND); styleHead.setAlignment(HorizontalAlignment.CENTER);//水平居中 XSSFFont font = xssfWorkbook.createFont(); font.setBold(true);//加粗 font.setFontHeight((short)240);//字体大小 styleHead.setFont(font); //创建style1 CellStyle style1 = xssfWorkbook.createCellStyle(); style1.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());//背景色 style1.setFillPattern(FillPatternType.SOLID_FOREGROUND); style1.setAlignment(HorizontalAlignment.CENTER);//水平居中 //创建style2 CellStyle style2 = xssfWorkbook.createCellStyle(); style2.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex());//背景色 style2.setFillPattern(FillPatternType.SOLID_FOREGROUND); style2.setAlignment(HorizontalAlignment.CENTER);//水平居中
sheet.setColumnWidth(4,3500);//给第5列设置宽度(tel栏)
优化后:
总结一下:
poi的简单使用还是不难的,说白了就数据库一个表对应一个sheet,表的一行对应一个row,表某一行的一个数据对应一个cell,嗯,就是这么简单。
说到调样式就非常头疼了,而且新版本的较之前改动比较大,百度出来的东西很多都没法用,勉强捣鼓了一些出来。
最后给自己打打气-——世上无难事,只要肯登攀!
最后推荐一个中文poi文档:
https://www.cnblogs.com/fqfanqi/p/6172223.html