springboot of data to export using poi (a)

Using the idea + restful style

First: the introduction of dependency:

        <!--poi-->
        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans</artifactId>
            <version>2.6.0</version>
        </dependency>
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>
        <!--poi-->

Step two:

File upload tools

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
 
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;
org.apache.poi.ss.usermodel.IndexedColors Import; 
Import org.apache.poi.ss.usermodel.Row; 
Import org.apache.poi.ss.usermodel.Sheet; 
Import org.apache.poi.ss.usermodel. Workbook; 
 
/ ** 
 * @author Qingmu 
 * @version created: December 28, 2017 4:53:29 PM 
 * class Description: POI export tool class 
 * / 
public class ExportPOIUtils { 
 
	// parameters: fileName: filename projects: a collection of objects columnNames: column name keys: map of Key 
	public static void start_download (<?> HttpServletResponse the Response, String fileName, the Projects List, 
			String [] columnNames, String [] Keys) throws IOException { 
		
		// the objects in the collection It corresponds to the attribute List <the Map <String, Object >> 
		List <the Map <String, Object List >> = createExcelRecord (Projects, Keys);
 
		ByteArrayOutputStream new new OS = ByteArrayOutputStream (); 
		try {
			// will be converted by the Workbook object streamed downloading 
			createWorkBook (List, Keys, the columnNames) .write (OS); 
		} the catch (IOException E) { 
			e.printStackTrace (); 
		} 
		byte [ ] os.toByteArray Content = (); 
		the InputStream A ByteArrayInputStream new new IS = (Content); 
		// set the response parameters can open the download page 
		response.reset (); 
		the response.setContentType ( "file application / vnd.ms-Excel; charset = UTF -8 "); 
		response.setHeader (" the Content-Disposition "," Attachment; filename = "+ new new String ((fileName +" * .xls ") the getBytes (),." ISO-8859-1 ")); 
		the ServletOutputStream OUT response.getOutputStream = (); 
		BufferedInputStream BIS = null;
		BufferedOutputStream bos = null; 
		the try { 
			BIS = new new BufferedInputStream (IS); 
			= new new BufferedOutputStream The BOS (OUT); 
			byte [] = BUFF new new byte [2048]; 
			int bytesRead;
			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();
		}
	}
	
	private static List<Map<String, Object>> createExcelRecord(List<?> projects, String[] keys) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "sheet");
		listmap.add(map);
		Object project=null;
		for (int j = 0; j < projects.size(); j++) {
			project=projects.get(j);
			Map<String, Object> mapValue = new HashMap<String, Object>();
			for(int i=0; i<keys.length; i++){
				mapValue.put(keys[i], getFieldValueByName(keys[i], project));
			}
 
			listmap.add(mapValue);
		}
		return listmap;
	}
	/** 
	 * 利用反射  根据属性名获取属性值 
	 * */  
	private static Object getFieldValueByName(String fieldName, Object o) {  
		try {    
			String firstLetter = fieldName.substring(0, 1).toUpperCase();    
			String getter = "get" + firstLetter + fieldName.substring(1);    
			Method method = o.getClass().getMethod(getter, new Class[] {});    
			Value = Method.invoke Object (O, new new Object [] {});     
			return value;     
        // manually set the column width. To first parameter set of columns; second column indicates the width parameter, n is the number of columns of pixels to be high.
		The catch} (Exception E) {     
			e.printStackTrace ();   
			return null;     
		}     
	} 
    / ** 
     * Create excel document object 
     * @param keys list set in the map key array 
     * @param columnNames excel column name of 
     * * / 
	Private static createWorkBook workbook (List <the Map <String, Object >> List, String [] Keys, columnNames String []) { 
        // create excel workbook 
        workbook wb = new new HSSFWorkbook (); 
        // create the first sheet (page), and designated 
        Sheet Sheet = wb.createSheet (List.get (0) .get ( "sheetName") toString ().); 
        // Create a first row
        for (int I = 0; I <keys.length; I ++) { 
            sheet.setColumnWidth ((Short) I, (Short) (35.7 * 150)); 
        } 
 
        Row Row = sheet.createRow ((Short) 0); 
 
        / / create two cell formatting 
        the CellStyle wb.createCellStyle CS = (); 
        the CellStyle wb.createCellStyle CS2 = (); 
 
        // create two fonts 
        the Font wb.createFont F = (); 
        the Font wb.createFont F2 = (); 
 
        / / create the first one font style (for the column name) 
        f.setFontHeightInPoints ((Short) 10); 
        f.setColor (IndexedColors.BLACK.getIndex ()); 
        f.setBoldweight (Font.BOLDWEIGHT_BOLD); 
 
        // create a second font style (for value) 
        f2.setFontHeightInPoints ((Short) 10);
        f2.setColor (IndexedColors.BLACK.getIndex ()); 
 
        // set the style of a first cell (for column names) 
        for (int i = 0; i <columnNames.length; i ++) { 
        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); 
 
        // Set the second cell pattern (a value ) 
        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 (the CellStyle. ALIGN_CENTER); 
        // set the name of the column 
            the Cell Cell row.createCell = (I); 
            cell.setCellValue (the columnNames [I]); 
            cell.setCellStyle (CS);
        } 
        // set values per row 
        for (I = Short. 1; I <list.size (); I ++) { 
            // row Row, Cell grid, Row Cell and are counted from 0 
            // Create line on the page Sheet 
            row sheet.createRow ROW1 = ((Short) I); 
            // Create a grid on row line 
            for (Short J = 0; J <keys.length; J ++) { 
                the 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; 
    } 
 
}

 The third step: write controller layer

import com.example.uploaddemo.util.ExportPOIUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qingmu
 * @date 
 */
public class UserController {
    @RequestMapping("exportList")
    public void exportList(HttpServletResponse response, String ids) {

        String fileName = "人员档案列表";

        List<The User> the Users = new new ArrayList <the User> (); 

        // column names 
        String columnNames [] = { "ID ", " name", "gender", "department", "affiliation", "email" ,
                 " phone "," mobile phone "," education / degree "," professional / specialist direction "," immediate supervisor "," account lockout " };
         // the Map of Key 
        String Keys [] = {" the above mentioned id "," userName " , "Gender", "Dept", "Unit", "In Email" ,
                 "Tel", "Phone", "Degree", "Major", "parentName", "isLocked" };
        try {
            ExportPOIUtils.start_download(response, fileName, users, columnNames, keys);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Here's one less user entity class, you can replace directly into your entity classes to be exported, ok.

Clean code, and efficient code.

 

Guess you like

Origin www.cnblogs.com/qingmuchuanqi48/p/11531187.html