java中的接口是类吗
272
2023-04-17
java导出数据库中Excel表格数据的方法
本篇文章基于java把数据库中的数据以Excel的方式导出,欢迎各位大神吐槽:
1、基于maven jar包引入如下:
2、首先创建数据库对应的实体类VO :UserVO(具体代码省略);
3、确定导出Excel内的title列,并放在数组里:String[] (具体代码省略);
4、编写导出Excel的方法:
传入参数:
Excel名称,Excel内的title列数组String[],数据集合List
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 jhttp://xl.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(BoldFoLaXTaSNvEnnt);
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;
}
}
在需要导出数据的时候调用此方法即可;
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~