java Excel匯出

來源:互聯網
上載者:User

標籤:org   flush   lock   bre   getname   style   stringbu   http   error   

Excel 匯出

@(JAVA)[匯出excel]

  • srv
/** *  * @param response  * @param list 需匯出的資料 */void createExcelWorkBookInfo(HttpServletResponse response, List<RtHtsyPositionCoverPojo> list);
  • srvImpl
@Override    public void createExcelWorkBookInfo(HttpServletResponse response, List<RtHtsyPositionCoverPojo> list) {        String nowStr = new Date().getTime() + "";        OutputStream out = null;        try {            out = response.getOutputStream();            response.reset();            response.setHeader("content-disposition",                    "attachment;filename=" + new String(("資訊匯出" + nowStr).getBytes("gb2312"), "ISO8859-1") + ".xls");            response.setContentType("APPLICATION/msexcel");            HSSFWorkbook workbook = new HSSFWorkbook();            //需要匯出的欄位            Map<String, String> fildsMap = new HashMap<>();            fildsMap.put("declareYear", "申報年度");            fildsMap.put("working","單位");            fildsMap.put("name","姓名");            fildsMap.put("udicTecOqCurVal","現任職資格");            fildsMap.put("udicTecOqDecVal","申請任職資格");            fildsMap.put("status","申報狀態");            excelService.export(list, fildsMap, workbook, null);            workbook.write(out);        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                // 強行將響應緩衝中的內容發送到目的地                response.flushBuffer();                if (out != null) {                    out.flush();                    out.close();                }            } catch (IOException e) {                LOGGER.error(e.toString());            }        }    }
  • ExcelService
public interface ExcelService {    <T> void export(List<T> results, Map<String, String> fildsMap, HSSFWorkbook wb, Integer rowNum);}
  • ExcelService
import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.commons.lang3.ArrayUtils;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFFont;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.hssf.util.HSSFColor;import org.springframework.stereotype.Service;import com.wisdombud.casic4.web.commonexcel.service.ExcelService;@Servicepublic class ExcelServiceImpl implements ExcelService{    public <T> void export(List<T> results, Map<String, String> fildsMap, HSSFWorkbook wb, Integer rowNum) {        if (rowNum == null) {            rowNum = rowMaxNum;        }        for (int i = 0; i < results.size(); i += rowNum) {            List<T> newlist = new ArrayList<>();            if ((i + rowNum) < results.size()) {                newlist = results.subList(i, i + rowNum);            } else {                newlist = results.subList(i, results.size());            }            HSSFSheet sheet = wb.createSheet();            for (int j = 0; j < fildsMap.size(); j++) {                sheet.setColumnWidth(i, 5000);            }            this.fillCommonHeader(wb, sheet, fildsMap);            this.fillCommonBody(newlist, sheet, wb, fildsMap);        }    }        private void fillCommonHeader(HSSFWorkbook wb, HSSFSheet sheet, Map<String, String> fildsMap) {        HSSFCellStyle style = wb.createCellStyle();        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);        HSSFFont font = wb.createFont();        font.setColor(HSSFColor.BLACK.index);        font.setFontHeightInPoints((short) 18);        style.setFont(font);        HSSFRow row = sheet.createRow(0);        int i = 0;        for (String key : fildsMap.keySet()) {            HSSFCell cell = row.createCell(i++);            String value = fildsMap.get(key);            cell.setCellValue(value);            cell.setCellStyle(style);        }    }        private <T> void fillCommonBody(List<T> results, HSSFSheet sheet, HSSFWorkbook wb, Map<String, String> fildsMap) {        HSSFCellStyle style = wb.createCellStyle();        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);        HSSFFont font = wb.createFont();        font.setColor(HSSFColor.BLACK.index);        font.setFontHeightInPoints((short) 16);        style.setFont(font);        int i = 1;        for (T inst : results) {            HSSFRow row = sheet.createRow(i++);            row.setRowStyle(style);            int j = 0;            for (String key : fildsMap.keySet()) {                HSSFCell cell = row.createCell(j++);                String val = setCell(key, inst);                cell.setCellValue(val);            }        }    }        @SuppressWarnings("rawtypes")    private <T> String setCell(String field, T data) {        String val = "";        Class clazz = data.getClass();        Field[] fields = ArrayUtils.addAll(clazz.getDeclaredFields(), clazz.getSuperclass().getDeclaredFields());        for (int i = 0; i < fields.length; i++) {            if (fields[i].getName().equals(field)) {                try {                    Object resultObject = invokeMethod(data, fields[i].getName(), null);                    if (resultObject == null) {                        resultObject = "";                    }                    val = resultObject.toString();                    break;                } catch (SecurityException | NoSuchMethodException | IllegalArgumentException | IllegalAccessException                        | InvocationTargetException e) {                    e.printStackTrace();                }            }        }        return val;    }            public Object invokeMethod(Object owner, String fieldname, Object[] args) throws SecurityException,            NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {        Class ownerClass = owner.getClass();                Method method = null;        method = ownerClass.getMethod(this.toGetter(fieldname));                Object object = null;        object = method.invoke(owner);                return object;        }        public String toGetter(String fieldname) {        if (fieldname == null || fieldname.length() == 0) {            return null;        }        if (fieldname.length() > 2) {            String second = fieldname.substring(1, 2);            if (second.equals(second.toUpperCase())) {                return new StringBuffer("get").append(fieldname).toString();            }        }        fieldname = new StringBuffer("get").append(fieldname.substring(0, 1).toUpperCase())                .append(fieldname.substring(1)).toString();        return fieldname;    }    }
  • maven
<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><dependency>    <groupId>org.apache.poi</groupId>    <artifactId>poi-scratchpad</artifactId>    <version>3.9</version></dependency>

java Excel匯出

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.