자바 가 POI 를 이용 하여 데이터 의 엑셀 내 보 내기
package com.y9zb.web.util;
import com.y9zb.core.SplitSet;
import com.y9zb.core.TimeUtil;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
/** * Excel * @author Guang * */ public class PoiExcelUtil {
private static final Logger logger =LoggerFactory.getLogger(PoiExcelUtil.class);
/** * Excel * @param excelName excel * @param list * @param fieldMap Map, excel * @param response response * @return */ public static <T> Boolean export(String excelName,List<T> list,LinkedHashMap<String, String> fieldMap,HttpServletResponse response){
// :
if (excelName==null || excelName=="") {
excelName = TimeUtil.getNoFormatToday()+TimeUtil.getNoFormatTime();
}
// response
response.reset();
response.setContentType("application/vnd.ms-excel"); // excel
try {
response.setHeader("Content-disposition", "attachment; filename="
+new String((excelName+"_"+TimeUtil.getNoFormatToday()+TimeUtil.getNoFormatTime()).getBytes("gb2312"), "ISO-8859-1") + ".xls");
} catch (UnsupportedEncodingException e1) {
logger.info(e1.getMessage());
return false;
}
try {
// WorkBook, Excel
HSSFWorkbook wb=new HSSFWorkbook();
List<List<T>> lists= SplitSet.split(list, 30000);
for (int j = 0; j < lists.size(); j++) {
// Workbook , sheet, Excel (sheet)
HSSFSheet sheet=wb.createSheet(excelName+"_"+(j+1));
//
sheet.setDefaultColumnWidth(18);
// ,
HSSFCellStyle style=wb.createCellStyle();
//
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//
fillSheet(sheet,lists.get(j),fieldMap,style);
}
//
OutputStream ouputStream = response.getOutputStream();
wb.write(ouputStream);
ouputStream.flush();
ouputStream.close();
} catch (Exception e) {
logger.info(" Excel !");
logger.error(e.getMessage());
return false;
}
return true;
}
/** * * * @param fieldName * * @param clazz * * @return */ public static Field getFieldByName(String fieldName, Class<?> clazz) {
logger.info(" :getFieldByName()");
//
Field[] selfFields = clazz.getDeclaredFields();
// ,
for (Field field : selfFields) {
// ,
if (field.getName().equals(fieldName)) {
return field;
}
}
// , ,
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null && superClazz != Object.class) {
//
return getFieldByName(fieldName, superClazz);
}
// ,
return null;
}
/** * * * @param fieldName * @param o * @return * @throws Exception * */ public static Object getFieldValueByName(String fieldName, Object o)
throws Exception {
logger.info(" :getFieldValueByName()");
Object value = null;
//
Field field = getFieldByName(fieldName, o.getClass());
// ,
if (field != null) {
field.setAccessible(true);// private, ,
value = field.get(o);// Field value
} else {
throw new Exception(o.getClass().getSimpleName() + " "
+ fieldName);
}
return value;
}
/** * , , * userName , , student.department.name * * @param fieldNameSequence * @param o * @return * @throws Exception * */ public static Object getFieldValueByNameSequence(String fieldNameSequence,
Object o) throws Exception {
logger.info(" , :getFieldValueByNameSequence()");
Object value = null;
// fieldNameSequence
String[] attributes = fieldNameSequence.split("\\.");
if (attributes.length == 1) {
value = getFieldValueByName(fieldNameSequence, o);
} else {
// , student.department.name
Object fieldObj = getFieldValueByName(attributes[0], o);
//
String subFieldNameSequence = fieldNameSequence
.substring(fieldNameSequence.indexOf(".") + 1);
//
value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
}
return value;
}
/** * * * @param sheet * excel * @param list * * @param fieldMap * Map * @param style * * @throws Exception * * */ public static <T> void fillSheet(HSSFSheet sheet, List<T> list,
LinkedHashMap<String, String> fieldMap,HSSFCellStyle style) throws Exception {
logger.info(" :fillSheet()");
//
String[] enFields = new String[fieldMap.size()];
String[] cnFields = new String[fieldMap.size()];
//
int count = 0;
for (Entry<String, String> entry : fieldMap.entrySet()) {
enFields[count] = entry.getKey();
cnFields[count] = entry.getValue();
count++;
}
// sheet 0 , poi Excel short
HSSFRow row=sheet.createRow((int)0);
//
for (int i = 0; i < cnFields.length; i++) {
HSSFCell cell=row.createCell(i);
cell.setCellValue(cnFields[i]);
cell.setCellStyle(style);
// sheet.autoSizeColumn(i);
}
//
for (int index = 0; index < list.size(); index++) {
row = sheet.createRow(index + 1);
//
T item = list.get(index);
for (int i = 0; i < enFields.length; i++) {
Object objValue = getFieldValueByNameSequence(enFields[i], item);
String fieldValue = objValue == null ? "" : objValue.toString();
row.createCell(i).setCellValue(fieldValue);
}
}
}
}
@RequestMapping(value = "query/excel/write")
public
@ResponseBody
HttpJsonResult<Boolean> queryExcel(HttpServletRequest request,
HttpServletResponse response, Map<String, Object> dataMap, String q_memberId, String q_memberName,
String q_memberPhone, String q_endTime, String q_startTime, String q_status) throws IOException {
HttpJsonResult<Boolean> jsonResult = new HttpJsonResult<Boolean>();
//queryMap--
Map<String, String> queryMap = new HashMap<String, String>();
queryMap.put("q_memberId", q_memberId);
queryMap.put("q_memberName", q_memberName);
queryMap.put("q_memberPhone", q_memberPhone);
queryMap.put("q_startTime", q_startTime);
queryMap.put("q_endTime", q_endTime);
queryMap.put("q_status", q_status);
queryMap.put("q_exportStatus", "0");
//count---
Integer count = pickingCardService.count(queryMap);
//index---
int index = 0;
if (count % 10000 == 0) {
index = count / 10000;
} else {
index = count / 10000 + 1;
}
List<PickingCard> pickingCardList = new ArrayList<>();
for (int i = 0; i < index; i++) {
PagerInfo pager = new PagerInfo();
pager.setPageIndex(i + 1);
pager.setPageSize(10000);
pager.setRowsCount(count);
ServiceResult<List<PickingCard>> serviceResult = pickingCardService.page(queryMap, pager);
pickingCardList.addAll(serviceResult.getResult());
}
// excel
String excelName = " ";
// excle map
LinkedHashMap<String, String> fieldMap = new LinkedHashMap<String, String>();
fieldMap.put("memberId", " ID");
fieldMap.put("memberName", " ");
fieldMap.put("memberPhone", " ");
fieldMap.put("createTimeString", " ");
fieldMap.put("statusString", " ");
for (int i = 0; i < pickingCardList.size(); i++) {
pickingCardList.get(i).setExportStatus(1);
pickingCardList.get(i).setCreateTimeString(TimeUtil.getDateTimeString(pickingCardList.get(i).getCreateTime()));
if (pickingCardList.get(i).getStatus() == 0) {
pickingCardList.get(i).setStatusString(" ");
} else {
pickingCardList.get(i).setStatusString(" ");
}
}
//
Boolean is = PoiExcelUtil.export(excelName, pickingCardList, fieldMap, response);
if (is) {
jsonResult.setRows(true);
jsonResult.setMessage(" ");
pickingCardService.updateBatch(pickingCardList);
} else {
jsonResult.setRows(false);
jsonResult.setMessage(" ");
}
return jsonResult;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.