java excel匯出工具類
阿新 • • 發佈:2019-01-04
使用的是apache poi與註解類實現:
maven:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14</version> </dependency>
1.註解類,將JAVA物件與excel標題對應
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * * @Description: excel匯出註解類 * @author kang * @date 2016年8月24日 */ @Target({ ElementType.METHOD, ElementType.FIELD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface ExcelField { //匯出欄位在excel中的名字 String title(); }
2.工具類:
import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * * @Description: excel匯出封裝類 * @author kang * @date 2016年8月24日 */ public class ExcelUtil { // 生成excel,list匯出的資料,list裡的實體class,sumData合計資料 public static <Q> XSSFWorkbook createExcel(List<Q> list, Class<Q> cls, Q sumData) throws IOException, IllegalArgumentException, IllegalAccessException { XSSFWorkbook wb = new XSSFWorkbook(); Field[] fields = cls.getDeclaredFields(); ArrayList<String> headList = new ArrayList<String>(); // 新增合計資料 if (sumData != null) { list.add(sumData); } for (Field f : fields) { ExcelField field = f.getAnnotation(ExcelField.class); if (field != null) { headList.add(field.title()); } } XSSFCellStyle style = getCellStyle(wb); XSSFSheet sheet = wb.createSheet(); // 設定Excel表的第一行即表頭 XSSFRow row = sheet.createRow(0); for (int i = 0; i < headList.size(); i++) { XSSFCell headCell = row.createCell(i); headCell.setCellType(Cell.CELL_TYPE_STRING); headCell.setCellStyle(style);// 設定表頭樣式 headCell.setCellValue(String.valueOf(headList.get(i))); // sheet.autoSizeColumn((short) i);// 設定單元格自適應 sheet.setColumnWidth(0, 15 * 256); } for (int i = 0; i < list.size(); i++) { XSSFRow rowdata = sheet.createRow(i + 1);// 建立資料行 Q q = list.get(i); Field[] ff = q.getClass().getDeclaredFields(); int j = 0; for (Field f : ff) { ExcelField field = f.getAnnotation(ExcelField.class); if (field == null) { continue; } f.setAccessible(true); Object obj = f.get(q); XSSFCell cell = rowdata.createCell(j); cell.setCellType(Cell.CELL_TYPE_STRING); // 當數字時 if (obj instanceof Integer) { cell.setCellValue((Integer)obj); // 將序號替換為123456 if (j == 0) cell.setCellValue(i + 1); } // 當為字串時 else if (obj instanceof String) cell.setCellValue((String)obj); // 當為布林時 else if (obj instanceof Boolean) cell.setCellValue((Boolean)obj); // 當為時間時 else if (obj instanceof Date) cell.setCellValue(DateUtils.getFormatDateStr((Date)obj, DateUtils.DEFAULT_FORMAT)); // 當為時間時 else if (obj instanceof Calendar) cell.setCellValue((Calendar)obj); // 當為小數時 else if (obj instanceof Double) cell.setCellValue((Double)obj); j++; } } if (sumData != null) { int rowIndex = list.size(); XSSFRow sumRow = sheet.getRow(rowIndex); XSSFCell sumCell = sumRow.getCell(0); sumCell.setCellStyle(style); sumCell.setCellValue("合計"); } return wb; } // 匯出 public static void writeExcel(HttpServletResponse response, String fileName, XSSFWorkbook wb) throws IOException { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment; filename=" + fileName); OutputStream ouputStream = null; try { ouputStream = response.getOutputStream(); wb.write(ouputStream); } finally { ouputStream.close(); } } // 表頭樣式 public static XSSFCellStyle getCellStyle(XSSFWorkbook wb) { XSSFCellStyle style = wb.createCellStyle(); Font font = wb.createFont(); font.setFontName("宋體"); font.setFontHeightInPoints((short)12);// 設定字型大小 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗 style.setFillForegroundColor(HSSFColor.LIME.index);// 設定背景色 style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setAlignment(HSSFCellStyle.SOLID_FOREGROUND);// 讓單元格居中 style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中 style.setWrapText(true);// 設定自動換行 style.setFont(font); return style; } }
3.使用:比如查詢結果List<User>,則在User物件上加上第一步的註解
public class User{
@ExcelField(title = "序號")
private String id;
@ExcelField(title = "部門")
private String deptName;
controller:
/**
* @Description: 查詢模組1表格資料
* @author kang
* @throws Exception
* @date 2016年8月25日
*/
@RequestMapping(value = "exportExcel", method = RequestMethod.POST)
public void exportExcel(Parameters parameters, HttpServletResponse response) throws Exception
{
List<User> list = userService.selectByParameters(parameters);
XSSFWorkbook wb = ExcelUtil.createExcel(list, User.class, null);
String filename = getExcelName("表格");
ExcelUtil.writeExcel(response, filename, wb);
}
// 轉化為excel名稱
private String getExcelName(String filename) throws UnsupportedEncodingException {
String excelName = StringUtils.join(filename, ".xlsx");
return URLEncoder.encode(excelName, "UTF-8");
}
前端:
1.如果是jsp ,有一個隱藏form,呼叫form的submit方法,下載完成後瀏覽器下方才會顯示已下載的檔案
<form id="exportExcel" action="${pageContext.request.contextPath}/user/exportExcel" method="post">
<input name="param" type="hidden">
</form>
2.或者如果用js
var f = document.createElement("form");
document.body.appendChild(f);
var input = document.createElement("input");
input.type = "hidden";
f.appendChild(input);
input.name = "param";
input.value = "xxx";
f.method="POST";
f.action = "xxx/exportExcel";
f.submit();
f.remove();