把数据库数据导出excel
时间:2021-07-01 10:21:17
帮助过:15人阅读
String fieldName = field.getName(); String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); System.out.println("我执行到了!!!" + getMethodName); Class cts = t.getClass(); System.out.println("我执行到了" + cts.toString()); Method getMethod = cts.getMethod(getMethodName, new Class[] {}); Object value = getMethod.invoke(t, new Object[] {}); String textValue = null; if (null != value) { if (value instanceof Integer) { int intValue = (Integer) value; cell.setCellValue(intValue); } else if (value instanceof Float) { float fValue = (float) value; textValue = Float.toString(fValue); cell.setCellValue(textValue); } else if (value instanceof Double) { double dValue = (double) value; cell.setCellValue(dValue); } else if (value instanceof Long) { long lValue = (long) value; cell.setCellValue(lValue); } else if (value instanceof byte[]) { byte[] bValue = (byte[]) value; // 有图片时设置行高为60px row.setHeightInPoints(60); HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6, index); anchor.setAnchorType(2); patriarch.createPicture(anchor, workbook.addPicture(bValue, HSSFWorkbook.PICTURE_TYPE_JPEG)); } else { textValue = value.toString(); } } else { textValue = ""; } if (textValue != null) { Pattern p = Pattern.compile("^//d+(//.//d+)?$"); Matcher matcher = p.matcher(textValue); if (matcher.matches()) { // 是数字当做double处理 cell.setCellValue(Double.parseDouble(textValue)); } else { HSSFRichTextString richString = new HSSFRichTextString(textValue); cell.setCellValue(richString); } } } if (length % initial_data == 0) { sheet = workbook.createSheet(title + length); // 设置表格默认宽度为15个字节 sheet.setDefaultColumnWidth(15); row = sheet.createRow(0); for (int i = 0; i < headers.length; i++) { HSSFCell cell = row.createCell(i); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); index = 0; } } } try { workbook.write(out); } catch (IOException e) { log.error(ExceptionUtils.getStackTrace(e)); log.error("导出数据失败!!"); } }}
上面呢就是我们全部的核心代码,我们把他做成了一个工具类,这样的写法看似很复杂,但是百万级的数据导出都是没有任何问题的,而且是能够直接导出图片的,功能强大,只是数据量大的话查询可能计较慢,。我这个测试时基于spring+mybatis+spring mvc架构实现的,大家可以看我的整个结构。
这是我的包结构:
调用代码 :
@RequestMapping("/excel")
public void excel() throws FileNotFoundException{
ExportExcel<Student> stuExcel = new ExportExcel<Student>();
String[] headers = {"编号","姓名","年龄","性别"};
List<Student> dataset = stu.query();
System.out.println("Student="+dataset);
Long date = new Date().getTime();
System.out.println("当前时间:"+date);
OutputStream os = new FileOutputStream("C:/Users/邓富奎/Desktop/1.xls");
stuExcel.exportExcel("Student信息表", headers, dataset, os);
Long end = new Date().getTime();
System.out.println("耗时:"+(end-date));
}
当我们调用这个方法后就会开始查询你要导出的数据,然后通过IO流把信息写入文件
执行完近20万条数据的导出,耗时:
最后在桌面生成excel文件:
把数据库数据导出excel
标签:反射 reflect nal time target 图片 没有 swa ict