本篇文章基于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;
}
}
在需要导出数据的时候调用此方法即可;