本示例是快速將查詢的結果導出到excel 中,如果用我的代碼只需要修改查詢數據的sql、excel文件名、excel的sheet標題、內容的標題即可。
POI簡介:Jakarta POI 是一套用於訪問微軟格式文檔的Java API。Jakarta POI有很多組件組成,其中有用於操作Excel格式文件的HSSF和用於操作Word的HWPF,在各種組件中目前只有用於操作Excel的HSSF相對成熟。
官方主頁http://poi.apache.org/index.html,
API文檔http://poi.apache.org/apidocs/index.html
使用方式:
創建數據庫(這個操作就不貼代碼了)
導入工程下db目錄的數據庫
創建類model(實際開發中換成自己的類),加上注解@ExcelField
public class Model { /** * 用戶昵稱 */ @ExcelField(title = "用戶昵稱") private String nick; /** * 用戶頭像url */ @ExcelField(title = "用戶頭像url") private String headUrl; /** * 用戶賬號 */ @ExcelField(title = "用戶賬號") private String userAcc; /** * 用戶手機號 */ @ExcelField(title = "用戶手機號") private String mobile; /** * 名字 */ @ExcelField(title = "名字") private String cardName; /** * '狀態,0待批,1不同意,2同意', */ @ExcelField(title = "狀態") private String state; /** * 說明 */ @ExcelField(title = "說明") private String describe; get/set...... }
編寫測試類
@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); } }
最后附上Excel注解的代碼
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工具類
// // 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(true); style.setVerticalAlignment((short)1); info.setCellValue("請嚴格按照表格說明的規范填寫,填寫不合法均會導入失敗;\r\n 1、表格已預置待發貨的訂貨號,請勿篡改;\r\n 2、物流公司名稱,請按照提供的標准填寫,必填,否則導入失敗;\r\n 3、物流單號,請按照實際物流公司單號填寫,必填,1-20字符以內"); 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 YException(YCode.C_1.code(), "請使用系統模板導入"); } if (!tableHeads[k].equals(cell.getStringCellValue())) { throw new YException(YCode.C_1.code(), "請使用系統模板導入"); } } } } else { i = 0; } if (sheet.getLastRowNum() > maxLimit) { throw new YException(YCode.C_1.code(), "單次導入不多於" + maxLimit + "個數據"); } 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數據異常"); } } }