java导出数据库中Excel表格数据的方法
程序员文章站
2024-02-24 10:53:58
本篇文章基于java把数据库中的数据以excel的方式导出,欢迎各位大神吐槽:
1、基于maven jar包引入如下:
...
本篇文章基于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; } }
在需要导出数据的时候调用此方法即可;
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。