java导出数据库中Excel表格数据的方法
作者:众星捧月
这篇文章主要为大家详细介绍了java导出数据库中Excel表格数据的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本篇文章基于java把数据库中的数据以Excel的方式导出,欢迎各位大神吐槽:
1、基于maven jar包引入如下:
<dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6.12</version> </dependency>
2、首先创建数据库对应的实体类VO :UserVO(具体代码省略);
3、确定导出Excel内的title列,并放在数组里:String[] (具体代码省略);
4、编写导出Excel的方法:
传入参数:
Excel名称,Excel内的title列数组String[],数据集合List<UserVO>
package bp.util; import java.io.OutputStream; import java.util.List; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Field; import jxl.Workbook; import jxl.format.Alignment; import jxl.format.Border; import jxl.format.BorderLineStyle; import jxl.format.VerticalAlignment; import jxl.write.Label; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; public class ExportExcel { public final static String exportExcel(String fileName, String[] Title, List listContent, HttpServletResponse response) { String result = "Excel文件导出成功!"; try { OutputStream os = response.getOutputStream(); response.reset(); response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("GB2312"), "ISO8859-1")); response.setContentType("application/msexcel"); WritableWorkbook workbook = Workbook.createWorkbook(os); WritableSheet sheet = workbook.createSheet("Sheet1", 0); jxl.SheetSettings sheetset = sheet.getSettings(); sheetset.setProtected(false); WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD); WritableCellFormat wcf_center = new WritableCellFormat(BoldFont); wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN); wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE); wcf_center.setAlignment(Alignment.CENTRE); wcf_center.setWrap(true); for (int i = 0; i < Title.length; i++) { sheet.setColumnView(i, 20); sheet.addCell(new Label(i, 0, Title[i], wcf_center)); } Field[] fields = null; int i = 1; for (Object obj : listContent) { fields = obj.getClass().getDeclaredFields(); int j = 0; for (Field v : fields) { v.setAccessible(true); Object va = v.get(obj); if (va == null) { va = ""; } sheet.addCell(new Label(j, i, va.toString(), wcf_center)); j++; } i++; } workbook.write(); workbook.close(); } catch (Exception e) { result = "Excel文件导出失败"; e.printStackTrace(); } return result; } }
在需要导出数据的时候调用此方法即可;
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。