JAVA Export data to EXCEL spreadsheet (simple)

This example is the rapid export query results to excel in, if I only need to modify the code sql query data, file names excel, excel sheet of the title, the title to the content.

POI Description: Jakarta POI is a Java API for accessing Microsoft format documents. Jakarta POI have many components, including an operation HSSF Excel format file and for operating HWPF Word, the various components are present only for the operation of Excel HSSF relatively mature.

The official home page http://poi.apache.org/index.html,

API documentation http://poi.apache.org/apidocs/index.html

 

Use:

Create a database (this operation will not put code)

Database under db into the project directory

Create a class model (replaced by the actual development of their own class), add comments @ExcelField

public  class the Model { 

    / ** 
     * Nickname 
     * / 
    @ExcelField (title = "Nickname" )
     Private String Nick; 

    / ** 
     * User Profile URL 
     * / 
    @ExcelField (title = "User Profile URL" )
     Private String HeadURL; 

    / ** 
     * user account 
     * / 
    @ExcelField (title = "user account" )
     Private String userAcc; 

    / ** 
     * mobile phone number 
     * / 
    @ExcelField (title = "mobile phone number" )
     Private String Mobile; 

    / ** 
     * name 
     * /
    @ExcelField (title = "name" )
     Private String CardName; 

    / ** 
     * 'state, pending 0, 1 disagree, 2 agree', 
     * / 
    @ExcelField (title = "Status" )
     Private String State;
     / ** 
     * Description 
     * / 
    @ExcelField (title = "Description" )
     Private String DESCRIBE; 


GET / SET ...... 
}

Write test classes

@SpringBootTest
@RunWith(SpringRunner.class)
public class ExportTest {
 
    @Autowired
    private ApiMapper apiMapper;
 
    /**
     * 导出测试
     * @throws Exception
     */
    @Test
    public void testExportLog() throws Exception {
       final String fileName = "提现审核统计表.xls";
        List<Model> list = apiMapper.findAll();
        
        ExcelUtil.writeExcel(response, fileName, list , Model.class);
    }
 

 
}

Finally, attach the Excel annotated code

import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelField {
    String title();
}
ExcelUtil Tools
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package cn.jss.common.util;

import cn.jss.common.YCode;
import cn.jss.common.YException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
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.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.ss.util.NumberToTextConverter;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class ExcelUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUtil.class);

    private ExcelUtil() {
    }

    public static <Q> void writeExcel(HttpServletResponse response, String fileName, List<Q> list, Class<Q> clazz) throws IOException, IllegalArgumentException, IllegalAccessException {
        HSSFWorkbook wb = new HSSFWorkbook();
        Field[] fields = getAllFields(clazz);
        ArrayList<String> headList = new ArrayList();
        Field[] var7 = fields;
        int var8 = fields.length;

        int i;
        for(i = 0; i < var8; ++i) {
            Field f = var7[i];
            ExcelField field = (ExcelField)f.getAnnotation(ExcelField.class);
            if (field != null) {
                headList.add(field.title());
            }
        }

        Sheet sheet = wb.createSheet();
        Row row = sheet.createRow(0);

        for(i = 0; i < headList.size(); ++i) {
            Cell headCell = row.createCell(i);
            headCell.setCellValue(String.valueOf(headList.get(i)));
        }

        if (null != list && !list.isEmpty()) {
            for(i = 0; i < list.size(); ++i) {
                Row rowData = sheet.createRow(i + 1);
                Q q = list.get(i);
                Field[] ff = getAllFields(q.getClass());
                int j = 0;
                Field[] var14 = ff;
                int var15 = ff.length;

                for(int var16 = 0; var16 < var15; ++var16) {
                    Field f = var14[var16];
                    ExcelField field = (ExcelField)f.getAnnotation(ExcelField.class);
                    if (field != null) {
                        f.setAccessible(true);
                        Object obj = f.get(q);
                        Cell cell = rowData.createCell(j);
                        cell.setCellType(1);
                        cell.setCellValue(String.valueOf(obj));
                        ++j;
                    }
                }
            }
        }

        response.setHeader("Content-Disposition", "attachment;filename=" + urlEncode(fileName));
        response.setContentType("application/ms-excel");
        ServletOutputStream ouPutStream = null;

        try {
            ouPutStream = response.getOutputStream();
            wb.write(ouPutStream);
        } finally {
            if (ouPutStream != null) {
                ouPutStream.close();
            }

        }

    }

    public static CellStyle getCellStyle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        style.setAlignment((short)1);
        style.setAlignment((short)2);
        style.setVerticalAlignment((short)1);
        style.setWrapText(true);
        return style;
    }

    public static Field[] getAllFields(Class clazz) {
        ArrayList fieldList;
        for(fieldList = new ArrayList(); clazz != null; clazz = clazz.getSuperclass()) {
            fieldList.addAll(new ArrayList(Arrays.asList(clazz.getDeclaredFields())));
        }

        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }

    public static final String urlEncode(String s) throws UnsupportedEncodingException {
        return URLEncoder.encode(s, "UTF-8");
    }

    public static HSSFWorkbook createExcelTemplate(String[] handers, List<String[]> downData, String[] downRows, String[] sendOrderList, String[] errorLogList, String[] expressFailList) {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet1 = wb.createSheet("批量发货");
        HSSFSheet sheet2 = wb.createSheet("Sheet2");
        sheet1.setDefaultColumnWidth(20);
        HSSFSheet translation = wb.createSheet("表格说明");
        translation.addMergedRegion(new CellRangeAddress(2, 19, 1, 10)); 
        HSSFRow Sheet3 = translation.createRow (2 ); 
        HSSFCell info = sheet3.createCell (. 1,. 1 ); 
        HSSFCellStyle style = wb.createCellStyle (); 
        style.setWrapText ( to true ); 
        style.setVerticalAlignment (( Short ). 1 ) ; 
        info.setCellValue ( "in strict accordance with the norms of instructions to fill in the form, fill out the illegal import will fail; \ r \ n 1, the table has to be shipped pre-order numbers, do not tamper with; \ r \ n 2, logistics company name, please fill in accordance with the standards provided, required, or the import fails; \ r \ n 3, the logistics a single number, please fill out the required logistics company in accordance with the actual single number within 1-20 character " ); 
        info. setCellStyle (style); 
        HSSFCell dealerOrderCell = null ;
         int I = 0 ;

         int i;
        for(i = sendOrderList.length; i < i; ++i) {
            HSSFRow row = sheet1.createRow(i + 1);
            dealerOrderCell = row.createCell(0, 1);
            dealerOrderCell.setCellValue(sendOrderList[i]);
        }

        HSSFRow row;
        HSSFCell logCell;
        int index;
        if (expressFailList != null && expressFailList.length > 0) {
            logCell = null;
            i = 0;

            for(index = errorLogList.length; i < index; ++i) {
                row = sheet1.createRow(i + 1);
                logCell = row.createCell(1, 1);
                logCell.setCellValue(expressFailList[i]);
            }
        }

        if (errorLogList != null && errorLogList.length > 0) {
            logCell = null;
            i = 0;

            for(index = errorLogList.length; i < index; ++i) {
                row = sheet1.createRow(i + 1);
                logCell = row.createCell(3, 1);
                logCell.setCellValue(errorLogList[i]);
            }
        }

        HSSFRow rowFirst = sheet1.createRow(0);

        for(i = 0; i < handers.length; ++i) {
            HSSFCell cell = rowFirst.createCell(i);
            sheet1.setColumnWidth(i, 5000);
            cell.setCellStyle(style);
            cell.setCellValue(handers[i]);
        }

        wb.setSheetHidden(1, true);
        String[] arr = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        index = 0;
        row = null;

        for(int r = 0; r < downRows.length; ++r) {
            String[] dlData = (String[])downData.get(r);
            int rownum = Integer.parseInt(downRows[r]);
            if (dlData.length < 5) {
                sheet1.addValidationData(setDataValidation(sheet1, dlData, 1, 500, rownum, rownum));
            } else {
                String strFormula = "Sheet2!$" + arr[index] + "$1:$" + arr[index] + "$500";
                sheet2.setColumnWidth(r, 4000);
                sheet1.addValidationData(SetDataValidation(strFormula, 1, 500, rownum, rownum));

                for(int j = 0; j < dlData.length; ++j) {
                    if (index == 0) {
                        row = sheet2.createRow(j);
                        sheet2.setColumnWidth(j, 4000);
                        row.createCell(0).setCellValue(dlData[j]);
                    } else {
                        int rowCount = sheet2.getLastRowNum();
                        if (j <= rowCount) {
                            sheet2.getRow(j).createCell(index).setCellValue(dlData[j]);
                        } else {
                            sheet2.setColumnWidth(j, 4000);
                            sheet2.createRow(j).createCell(index).setCellValue(dlData[j]);
                        }
                    }
                }

                ++index;
            }
        }

        return wb;
    }

    private static HSSFDataValidation SetDataValidation(String strFormula, int firstRow, int endRow, int firstCol, int endCol) {
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        DVConstraint constraint = DVConstraint.createFormulaListConstraint(strFormula);
        HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
        dataValidation.createErrorBox("Error", "Error");
        dataValidation.createPromptBox("", (String)null);
        return dataValidation;
    }

    private static DataValidation setDataValidation(Sheet sheet, String[] textList, int firstRow, int endRow, int firstCol, int endCol) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createExplicitListConstraint(textList);
        constraint.setExplicitListValues(textList);
        CellRangeAddressList regions = new CellRangeAddressList((short)firstRow, (short)endRow, (short)firstCol, (short)endCol);
        DataValidation data_validation = helper.createValidation(constraint, regions);
        return data_validation;
    }

    public static List excelForList(MultipartFile file, Class<?> clazz, Boolean titleExist, String[] tableHeads, Integer maxLimit) throws YException {
        ArrayList list = new ArrayList();

        try {
            Object wb = null;

            try {
                InputStream input = file.getInputStream();
                wb = new HSSFWorkbook(input);
            } catch (Exception var23) {
                InputStream input = file.getInputStream();
                wb = new XSSFWorkbook(input);
            }

            Sheet sheet = ((Workbook)wb).getSheetAt(0);
            Row row;
            int i;
            if (titleExist) {
                i = 1;
                if (null != tableHeads && tableHeads.length > 0) {
                    row = sheet.getRow(0);
                    int num = row.getPhysicalNumberOfCells();
                    if (num != tableHeads.length) {
                        throw new YException(YCode.C_1.code(), "请使用系统模板导入");
                    }

                    for(int k = 0; k < tableHeads.length; ++k) {
                        Cell cell = row.getCell(k);
                        if (null == cell || null == cell.getStringCellValue()) {
                            throw new newYException (YCode.C_1.code (), "using the template into system" ); 
                        } 

                        IF (! {TableHeads [K] .equals (cell.getStringCellValue ()))
                             the throw  new new YException (YCode.C_1.code (), "Please use the template into system" ); 
                        } 
                    } 
                } 
            } the else { 
                I = 0 ; 
            } 

            IF (sheet.getLastRowNum ()> MAXLIMIT) {
                 the throw  new new YException (YCode.C_1.code (), "not more than a single import "+ maxLimit +" data " ); 
            } the else {
                while(i <= sheet.getLastRowNum()) {
                    row = sheet.getRow(i);
                    Object object = clazz.newInstance();
                    Field[] fields = clazz.getDeclaredFields();
                    int j = 0;
                    Field[] var13 = fields;
                    int var14 = fields.length;

                    for(int var15 = 0; var15 < var14; ++var15) {
                        Field field = var13[var15];
                        String fieldName = field.getName();
                        PropertyDescriptor pd = new PropertyDescriptor(fieldName, clazz);
                        Method getMethod = pd.getWriteMethod();
                        Cell cell = row.getCell(j++);
                        int type = cell.getCellType();
                        if (type == 4) {
                            boolean value = cell.getBooleanCellValue();
                            getMethod.invoke(object, String.valueOf(value));
                        } else if (type == 0) {
                            Double d = cell.getNumericCellValue();
                            getMethod.invoke(object, NumberToTextConverter.toText(d));
                        } else if (type == 1) {
                            String value = cell.getStringCellValue();
                            getMethod.invoke(object, new String(value));
                        }
                    }

                    list.add(object);
                    ++i;
                }

                return list;
            }
        } catch (YException var24) {
            throw new YException(var24.getStatus(), var24.getMessage());
        } catch (Exception var25) {
            LOGGER.error("excelForList e=>", var25);
            throw new YException(YCode.C_400.code(), "解析Excel数据异常");
        }
    }
}

 

 

Guess you like

Origin www.cnblogs.com/senhelpa-vivo/p/12107395.html