a458848e6e3e5ab8852a0e7882f160f9a489a0d2.svn-base 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. package cn.com.goldenwater.dcproj.utils.impexcel;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alibaba.fastjson.JSONObject;
  4. import org.apache.poi.hpsf.SummaryInformation;
  5. import org.apache.poi.hssf.usermodel.*;
  6. import org.apache.poi.hssf.util.HSSFColor;
  7. import org.apache.poi.ss.usermodel.*;
  8. import org.apache.poi.ss.util.CellRangeAddress;
  9. import org.apache.poi.ss.util.CellRangeAddressList;
  10. import org.apache.poi.xssf.streaming.SXSSFCell;
  11. import org.apache.poi.xssf.streaming.SXSSFRow;
  12. import org.apache.poi.xssf.streaming.SXSSFSheet;
  13. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  14. import javax.servlet.ServletOutputStream;
  15. import javax.servlet.http.HttpServletResponse;
  16. import java.io.*;
  17. import java.math.BigDecimal;
  18. import java.text.SimpleDateFormat;
  19. import java.util.Date;
  20. import java.util.Iterator;
  21. import java.util.LinkedHashMap;
  22. import java.util.Map;
  23. /**
  24. * <p>
  25. * 导出Excel的一些公用方法
  26. * </p>
  27. *
  28. * @author liyz
  29. * @version 2.0
  30. * @date 2019/3/6 9:43
  31. */
  32. public class ExportExcel {
  33. /**
  34. * 本地测试方法
  35. */
  36. public static void main(String[] args) throws IOException {
  37. int count = 100000;
  38. JSONArray ja = new JSONArray();
  39. for (int i = 0; i < 100000; i++) {
  40. Student s = new Student();
  41. s.setName("POI" + i);
  42. s.setAge(i);
  43. s.setBirthday(new Date());
  44. s.setHeight(i);
  45. s.setWeight(i);
  46. s.setSex(i / 2 == 0 ? false : true);
  47. ja.add(s);
  48. }
  49. Map<String, String> headMap = new LinkedHashMap<String, String>();
  50. headMap.put("name", "姓名");
  51. headMap.put("age", "年龄");
  52. headMap.put("birthday", "生日");
  53. headMap.put("height", "身高");
  54. headMap.put("weight", "体重");
  55. headMap.put("sex", "性别");
  56. String title = "测试";
  57. OutputStream outXls = new FileOutputStream("C:/Users/a/Desktop/a.xls");
  58. System.out.println("正在导出xls...");
  59. Date d = new Date();
  60. ExportExcel.exportExcel(title, headMap, ja, null, 0, outXls);
  61. System.out.println("共" + count + "条数据,执行" + (System.currentTimeMillis() - d.getTime()) + "ms");
  62. outXls.close();
  63. // OutputStream outXlsx = new FileOutputStream("C:/Users/a/Desktop/b.xlsx");
  64. // System.out.println("正在导出xlsx....");
  65. // Date d2 = new Date();
  66. // ExcelUtils.exportExcelX(title,headMap,ja,null,0,outXlsx);
  67. // System.out.println("共"+count+"条数据,执行"+(System.currentTimeMillis()-d2.getTime())+"ms");
  68. // outXlsx.close();
  69. }
  70. /**
  71. * 未定义的字段
  72. */
  73. private static final String NO_DEFINE = "no_define";
  74. /**
  75. * 默认日期格式
  76. */
  77. private static final String DEFAULT_DATE_PATTERN = "yyyy年MM月dd日";
  78. /**
  79. * 默认列宽
  80. */
  81. private static final int DEFAULT_COLOUMN_WIDTH = 17;
  82. /**
  83. * 导出Excel 97(.xls)格式 ,少量数据
  84. *
  85. * @param title 标题行
  86. * @param headMap 属性-列名
  87. * @param jsonArray 数据集
  88. * @param datePattern 日期格式,null则用默认日期格式
  89. * @param colWidth 列宽 默认 至少17个字节
  90. * @param out 输出流
  91. */
  92. public static void exportExcel(String title, Map<String, String> headMap, JSONArray jsonArray, String datePattern, int colWidth, OutputStream out) {
  93. if (datePattern == null) {
  94. datePattern = DEFAULT_DATE_PATTERN;
  95. }
  96. // 声明一个工作薄
  97. HSSFWorkbook workbook = new HSSFWorkbook();
  98. workbook.createInformationProperties();
  99. workbook.getDocumentSummaryInformation().setCompany("*****公司");
  100. SummaryInformation si = workbook.getSummaryInformation();
  101. //填加xls文件作者信息
  102. si.setAuthor("JinShui");
  103. //填加xls文件创建程序信息
  104. si.setApplicationName("导出程序");
  105. //填加xls文件最后保存者信息
  106. si.setLastAuthor("最后保存者信息");
  107. //填加xls文件作者信息
  108. si.setComments("JinShui is a company!");
  109. //填加xls文件标题信息
  110. si.setTitle("POI导出Excel");
  111. //填加文件主题信息
  112. si.setSubject("POI导出Excel");
  113. si.setCreateDateTime(new Date());
  114. // 表头样式
  115. HSSFCellStyle titleStyle = workbook.createCellStyle();
  116. titleStyle.setAlignment(HorizontalAlignment.CENTER);
  117. HSSFFont titleFont = workbook.createFont();
  118. titleFont.setFontHeightInPoints((short) 20);
  119. // titleFont.setBoldweight((short) 700);
  120. titleFont.setBold(true);
  121. titleStyle.setFont(titleFont);
  122. // 列头样式
  123. HSSFCellStyle headerStyle = workbook.createCellStyle();
  124. headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  125. headerStyle.setBorderBottom(BorderStyle.THIN);
  126. headerStyle.setBorderLeft(BorderStyle.THIN);
  127. headerStyle.setBorderRight(BorderStyle.THIN);
  128. headerStyle.setBorderTop(BorderStyle.THIN);
  129. headerStyle.setAlignment(HorizontalAlignment.CENTER);
  130. HSSFFont headerFont = workbook.createFont();
  131. headerFont.setFontHeightInPoints((short) 12);
  132. // headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  133. headerFont.setBold(true);
  134. headerStyle.setFont(headerFont);
  135. // 单元格样式
  136. HSSFCellStyle cellStyle = workbook.createCellStyle();
  137. cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  138. cellStyle.setBorderBottom(BorderStyle.THIN);
  139. cellStyle.setBorderLeft(BorderStyle.THIN);
  140. cellStyle.setBorderRight(BorderStyle.THIN);
  141. cellStyle.setBorderTop(BorderStyle.THIN);
  142. cellStyle.setAlignment(HorizontalAlignment.CENTER);
  143. cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  144. HSSFFont cellFont = workbook.createFont();
  145. // cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
  146. cellFont.setBold(true);
  147. cellStyle.setFont(cellFont);
  148. // 生成一个(带标题)表格
  149. HSSFSheet sheet = workbook.createSheet();
  150. // 声明一个画图的顶级管理器
  151. HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
  152. // 定义注释的大小和位置,详见文档
  153. HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
  154. 0, 0, 0, (short) 4, 2, (short) 6, 5));
  155. // 设置注释内容
  156. comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));
  157. // 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.
  158. comment.setAuthor("JinShui");
  159. //设置列宽
  160. //至少字节数
  161. int minBytes = colWidth < DEFAULT_COLOUMN_WIDTH ? DEFAULT_COLOUMN_WIDTH : colWidth;
  162. int[] arrColWidth = new int[headMap.size()];
  163. // 产生表格标题行,以及设置列宽
  164. String[] properties = new String[headMap.size()];
  165. String[] headers = new String[headMap.size()];
  166. int ii = 0;
  167. for (Iterator<String> iter = headMap.keySet().iterator(); iter.hasNext(); ) {
  168. String fieldName = iter.next();
  169. properties[ii] = fieldName;
  170. headers[ii] = fieldName;
  171. int bytes = fieldName.getBytes().length;
  172. arrColWidth[ii] = bytes < minBytes ? minBytes : bytes;
  173. sheet.setColumnWidth(ii, arrColWidth[ii] * 256);
  174. ii++;
  175. }
  176. // 遍历集合数据,产生数据行
  177. int rowIndex = 0;
  178. for (Object obj : jsonArray) {
  179. if (rowIndex == 65535 || rowIndex == 0) {
  180. //如果数据超过了,则在第二页显示
  181. if (rowIndex != 0) {
  182. sheet = workbook.createSheet();
  183. }
  184. //表头 rowIndex=0
  185. HSSFRow titleRow = sheet.createRow(0);
  186. titleRow.createCell(0).setCellValue(title);
  187. titleRow.getCell(0).setCellStyle(titleStyle);
  188. sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));
  189. //列头 rowIndex =1
  190. HSSFRow headerRow = sheet.createRow(1);
  191. for (int i = 0; i < headers.length; i++) {
  192. headerRow.createCell(i).setCellValue(headers[i]);
  193. headerRow.getCell(i).setCellStyle(headerStyle);
  194. }
  195. //数据内容从 rowIndex=2开始
  196. rowIndex = 2;
  197. }
  198. JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
  199. HSSFRow dataRow = sheet.createRow(rowIndex);
  200. for (int i = 0; i < properties.length; i++) {
  201. HSSFCell newCell = dataRow.createCell(i);
  202. Object o = jo.get(properties[i]);
  203. String cellValue = "";
  204. if (o == null) {
  205. cellValue = "";
  206. } else if (o instanceof Date) {
  207. cellValue = new SimpleDateFormat(datePattern).format(o);
  208. } else {
  209. cellValue = o.toString();
  210. }
  211. newCell.setCellValue(cellValue);
  212. newCell.setCellStyle(cellStyle);
  213. }
  214. rowIndex++;
  215. }
  216. try {
  217. workbook.write(out);
  218. workbook.close();
  219. } catch (IOException e) {
  220. e.printStackTrace();
  221. }
  222. }
  223. /**
  224. * 导出Excel 2007 OOXML (.xlsx)格式
  225. *
  226. * @param title 标题行
  227. * @param headMap 属性-列头
  228. * @param jsonArray 数据集
  229. * @param datePattern 日期格式,传null值则默认 年月日
  230. * @param colWidth 列宽 默认 至少17个字节
  231. * @param out 输出流
  232. */
  233. public static void exportExcelX(String title, Map<String, String> headMap, JSONArray jsonArray, String datePattern, int colWidth, OutputStream out) {
  234. if (datePattern == null) {
  235. datePattern = DEFAULT_DATE_PATTERN;
  236. }
  237. // 声明一个工作薄
  238. //缓存
  239. SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
  240. workbook.setCompressTempFiles(true);
  241. //表头样式
  242. CellStyle titleStyle = workbook.createCellStyle();
  243. titleStyle.setAlignment(HorizontalAlignment.CENTER);
  244. Font titleFont = workbook.createFont();
  245. titleFont.setFontHeightInPoints((short) 20);
  246. // titleFont.setBoldweight((short) 700);
  247. titleFont.setBold(true);
  248. titleStyle.setFont(titleFont);
  249. // 列头样式
  250. CellStyle headerStyle = workbook.createCellStyle();
  251. headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  252. headerStyle.setBorderBottom(BorderStyle.THIN);
  253. headerStyle.setBorderLeft(BorderStyle.THIN);
  254. headerStyle.setBorderRight(BorderStyle.THIN);
  255. headerStyle.setBorderTop(BorderStyle.THIN);
  256. headerStyle.setAlignment(HorizontalAlignment.CENTER);
  257. headerStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.index);
  258. Font headerFont = workbook.createFont();
  259. headerFont.setFontHeightInPoints((short) 12);
  260. // headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  261. headerFont.setBold(true);
  262. headerStyle.setFont(headerFont);
  263. // 单元格样式
  264. CellStyle cellStyle = workbook.createCellStyle();
  265. cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  266. cellStyle.setBorderBottom(BorderStyle.THIN);
  267. cellStyle.setBorderLeft(BorderStyle.THIN);
  268. cellStyle.setBorderRight(BorderStyle.THIN);
  269. cellStyle.setBorderTop(BorderStyle.THIN);
  270. cellStyle.setAlignment(HorizontalAlignment.CENTER);
  271. cellStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.index);
  272. cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  273. Font cellFont = workbook.createFont();
  274. // cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
  275. cellFont.setBold(true);
  276. cellStyle.setFont(cellFont);
  277. // 生成一个(带标题)表格
  278. SXSSFSheet sheet = workbook.createSheet();
  279. //设置列宽
  280. //至少字节数
  281. int minBytes = colWidth < DEFAULT_COLOUMN_WIDTH ? DEFAULT_COLOUMN_WIDTH : colWidth;
  282. int[] arrColWidth = new int[headMap.size()];
  283. // 产生表格标题行,以及设置列宽
  284. String[] properties = new String[headMap.size()];
  285. String[] headers = new String[headMap.size()];
  286. int ii = 0;
  287. for (String fieldName : headMap.keySet()) {
  288. properties[ii] = fieldName;
  289. headers[ii] = headMap.get(fieldName);
  290. int bytes = fieldName.getBytes().length;
  291. arrColWidth[ii] = bytes < minBytes ? minBytes : bytes;
  292. sheet.setColumnWidth(ii, arrColWidth[ii] * 256);
  293. ii++;
  294. }
  295. // 遍历集合数据,产生数据行
  296. int rowIndex = 0;
  297. for (Object obj : jsonArray) {
  298. if (rowIndex == 65535 || rowIndex == 0) {
  299. if (rowIndex != 0) {
  300. //如果数据超过了,则在第二页显示
  301. sheet = workbook.createSheet();
  302. }
  303. //表头 rowIndex=0
  304. SXSSFRow titleRow = sheet.createRow(0);
  305. titleRow.createCell(0).setCellValue(title);
  306. titleRow.getCell(0).setCellStyle(titleStyle);
  307. sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));
  308. //列头 rowIndex =1
  309. SXSSFRow headerRow = sheet.createRow(1);
  310. for (int i = 0; i < headers.length; i++) {
  311. headerRow.createCell(i).setCellValue(headers[i]);
  312. headerRow.getCell(i).setCellStyle(headerStyle);
  313. }
  314. //数据内容从 rowIndex=2开始
  315. rowIndex = 2;
  316. }
  317. JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
  318. SXSSFRow dataRow = sheet.createRow(rowIndex);
  319. for (int i = 0; i < properties.length; i++) {
  320. SXSSFCell newCell = dataRow.createCell(i);
  321. Object o = jo.get(properties[i]);
  322. String cellValue = "";
  323. if (o == null) {
  324. cellValue = "";
  325. } else if (o instanceof Date) {
  326. cellValue = new SimpleDateFormat(datePattern).format(o);
  327. } else if (o instanceof Float || o instanceof Double) {
  328. cellValue = new BigDecimal(o.toString()).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
  329. } else {
  330. cellValue = o.toString();
  331. }
  332. newCell.setCellValue(cellValue);
  333. newCell.setCellStyle(cellStyle);
  334. }
  335. rowIndex++;
  336. }
  337. try {
  338. workbook.write(out);
  339. workbook.close();
  340. workbook.dispose();
  341. } catch (IOException e) {
  342. e.printStackTrace();
  343. }
  344. }
  345. /**
  346. * Web 导出excel
  347. */
  348. public static void downloadExcelFile(String title, Map<String, String> headMap, JSONArray ja, HttpServletResponse response) {
  349. try {
  350. ByteArrayOutputStream os = new ByteArrayOutputStream();
  351. ExportExcel.exportExcelX(title, headMap, ja, null, 0, os);
  352. byte[] content = os.toByteArray();
  353. InputStream is = new ByteArrayInputStream(content);
  354. // 设置response参数,可以打开下载页面
  355. response.reset();
  356. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
  357. response.setHeader("Content-Disposition", "attachment;filename=" + new String((title + ".xlsx").getBytes(), "iso-8859-1"));
  358. response.setContentLength(content.length);
  359. ServletOutputStream outputStream = response.getOutputStream();
  360. BufferedInputStream bis = new BufferedInputStream(is);
  361. BufferedOutputStream bos = new BufferedOutputStream(outputStream);
  362. byte[] buff = new byte[8192];
  363. int bytesRead;
  364. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  365. bos.write(buff, 0, bytesRead);
  366. }
  367. bis.close();
  368. bos.close();
  369. outputStream.flush();
  370. outputStream.close();
  371. } catch (Exception e) {
  372. e.printStackTrace();
  373. }
  374. }
  375. /**
  376. * 下载Excel的重载方法(简化常用)
  377. *
  378. * @param response HttpServletResponse
  379. * @param os 字节数据输出流
  380. * @param fileName 文件名称
  381. */
  382. public static void downloadExcelFile(HttpServletResponse response, ByteArrayOutputStream os, String fileName) {
  383. try {
  384. byte[] content = os.toByteArray();
  385. InputStream is = new ByteArrayInputStream(content);
  386. // 设置response参数,可以打开下载页面
  387. response.reset();
  388. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
  389. response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
  390. response.setContentLength(content.length);
  391. ServletOutputStream outputStream = response.getOutputStream();
  392. BufferedInputStream bis = new BufferedInputStream(is);
  393. BufferedOutputStream bos = new BufferedOutputStream(outputStream);
  394. byte[] buff = new byte[8192];
  395. int bytesRead;
  396. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  397. bos.write(buff, 0, bytesRead);
  398. }
  399. bis.close();
  400. bos.close();
  401. outputStream.flush();
  402. outputStream.close();
  403. } catch (Exception e) {
  404. e.printStackTrace();
  405. } finally {
  406. if (os != null) {
  407. try {
  408. os.close();
  409. } catch (IOException e) {
  410. e.printStackTrace();
  411. }
  412. }
  413. }
  414. }
  415. public static ByteArrayOutputStream getByteArrayOut(FileInputStream fis) throws Exception {
  416. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  417. byte[] buff = new byte[1024];
  418. int bytesRead;
  419. while ((bytesRead = fis.read(buff, 0, buff.length)) != -1) {
  420. baos.write(buff, 0, bytesRead);
  421. }
  422. baos.close();
  423. fis.close();
  424. return baos;
  425. }
  426. /**
  427. * 导出EXCEL时动态创建一个下拉列表
  428. *
  429. * @param groupNamesList 数据集
  430. * @param firstRow 下拉框从第几行开始,默认最终行结束
  431. * @param firstCol 下拉框从第几列开始
  432. * @param fis 输入流
  433. * @param bos 输出流
  434. * @return 输出流
  435. */
  436. public static ByteArrayOutputStream createListBox(String[] groupNamesList, int firstRow, int firstCol, FileInputStream fis, ByteArrayOutputStream bos) {
  437. try {
  438. if (groupNamesList.length == 0) {
  439. return bos;
  440. }
  441. HSSFWorkbook workBook = new HSSFWorkbook(fis);
  442. // 先创建一个隐藏的Sheet来存放下拉列表
  443. HSSFSheet hidden = workBook.createSheet("hidden");
  444. HSSFCell cell;
  445. for (int i = 0, length = groupNamesList.length; i < length; i++) {
  446. String name = groupNamesList[i];
  447. HSSFRow row = hidden.createRow(i);
  448. cell = row.createCell(0);
  449. cell.setCellValue(name);
  450. }
  451. Name namedCell = workBook.createName();
  452. namedCell.setNameName("hidden");
  453. namedCell.setRefersToFormula("hidden!$A$1:$A$" + groupNamesList.length);
  454. //加载数据,将名称为hidden的列当成下拉框内容
  455. DVConstraint constraint = DVConstraint.createFormulaListConstraint("hidden");
  456. HSSFSheet sheet = workBook.getSheetAt(0);
  457. // 对指定单元区域生效
  458. CellRangeAddressList regions = new CellRangeAddressList(firstRow, 65535, firstCol, firstCol);
  459. // 绑定下拉框和作用区域
  460. HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
  461. //将名字为hidden的sheet设置为隐藏
  462. workBook.setSheetHidden(workBook.getSheetIndex("hidden"), true);
  463. // 对sheet页生效
  464. sheet.addValidationData(dataValidation);
  465. workBook.write(bos);
  466. bos.flush();
  467. } catch (Exception e) {
  468. e.printStackTrace();
  469. } finally {
  470. if (fis != null) {
  471. try {
  472. fis.close();
  473. } catch (IOException e) {
  474. e.printStackTrace();
  475. }
  476. }
  477. }
  478. return bos;
  479. }
  480. /**
  481. * 导出EXCEL时动态创建一个下拉列表
  482. *
  483. * @param groupNamesList 数据集
  484. * @param firstRow 下拉框从第几行开始,默认最终行结束
  485. * @param firstCol 下拉框从第几列开始
  486. * @param workBook WorkBook
  487. * @return 输出流
  488. */
  489. public static ByteArrayOutputStream createListBox(String[] groupNamesList, int firstRow, int firstCol, Workbook workBook) {
  490. // 隐藏Sheet的名称最多支持31个字符,时间戳13位
  491. String hiddenSheetName = "hidden" + System.currentTimeMillis();
  492. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  493. try {
  494. if (groupNamesList.length == 0 || workBook == null) {
  495. if(workBook != null){
  496. workBook.write(bos);
  497. bos.flush();
  498. bos.close();
  499. }
  500. return bos;
  501. }
  502. // 先创建一个隐藏的Sheet来存放下拉列表
  503. Sheet hidden = workBook.createSheet(hiddenSheetName);
  504. Cell cell;
  505. for (int i = 0, length = groupNamesList.length; i < length; i++) {
  506. String name = groupNamesList[i];
  507. Row row = hidden.createRow(i);
  508. cell = row.createCell(0);
  509. cell.setCellValue(name);
  510. }
  511. Name namedCell = workBook.createName();
  512. namedCell.setNameName(hiddenSheetName);
  513. namedCell.setRefersToFormula(hiddenSheetName + "!$A$1:$A$" + groupNamesList.length);
  514. //加载数据,将名称为hidden的列当成下拉框内容
  515. DVConstraint constraint = DVConstraint.createFormulaListConstraint(hiddenSheetName);
  516. Sheet sheet = workBook.getSheetAt(0);
  517. // 对指定单元区域生效
  518. CellRangeAddressList regions = new CellRangeAddressList(firstRow, 65535, firstCol, firstCol);
  519. // 绑定下拉框和作用区域
  520. HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
  521. //将名字为hidden的sheet设置为隐藏
  522. workBook.setSheetHidden(workBook.getSheetIndex(hiddenSheetName), true);
  523. // 对sheet页生效
  524. sheet.addValidationData(dataValidation);
  525. workBook.write(bos);
  526. bos.flush();
  527. } catch (Exception e) {
  528. e.printStackTrace();
  529. } finally {
  530. try {
  531. bos.close();
  532. } catch (IOException e) {
  533. e.printStackTrace();
  534. }
  535. }
  536. return bos;
  537. }
  538. }
  539. class Student {
  540. private String name;
  541. private int age;
  542. private Date birthday;
  543. private float height;
  544. private double weight;
  545. private boolean sex;
  546. public String getName() {
  547. return name;
  548. }
  549. public void setName(String name) {
  550. this.name = name;
  551. }
  552. public Integer getAge() {
  553. return age;
  554. }
  555. public Date getBirthday() {
  556. return birthday;
  557. }
  558. public void setBirthday(Date birthday) {
  559. this.birthday = birthday;
  560. }
  561. public float getHeight() {
  562. return height;
  563. }
  564. public void setHeight(float height) {
  565. this.height = height;
  566. }
  567. public double getWeight() {
  568. return weight;
  569. }
  570. public void setWeight(double weight) {
  571. this.weight = weight;
  572. }
  573. public boolean isSex() {
  574. return sex;
  575. }
  576. public void setSex(boolean sex) {
  577. this.sex = sex;
  578. }
  579. public void setAge(Integer age) {
  580. this.age = age;
  581. }
  582. }