java相关:jxl 导出数据到excel的实例讲解
发布于 2020-7-18|
下面小妖就为大家分享一篇jxl 导出数据到excel的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小妖过来看看吧
优点:Jxl对中文支持非常好,操作简单,方法看名知意。Jxl是纯javaAPI,在跨平台上表现的非常完美,代码可以再windows或者Linux上运行而无需重新编写支持Excel 95-2000的所有版本(网上说目前可以支持Excel2007了,还没有尝试过)生成Excel 2000标准格式支持字体、数字、日期操作能够修饰单元格属性支持图像和图表,但是这套API对图形和图表的支持很有限,而且仅仅识别PNG格式。缺点:效率低,图片支持不完善,对格式的支持不如POI强大案例:
```xhtml
String times = (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());
String fname = "系统日志" + times; // 文件名
List list=logsService.selectForList(hql.toString());
String path = request.getSession().getServletContext().getRealPath("/")
+ "xls/"
+ (new SimpleDateFormat("yyyyMMdd")).format(new Date());
File file = new File(path);
// 如果文件夹不存在则创建
if (!file.exists() && !file.isDirectory()) {
file.mkdir();
}
response.setContentType("application/vnd.ms-excel;charset=utf-8");// // 指定文件的保存类型。
response.setCharacterEncoding("utf-8");
ExportUtil.writer_log(request,fname, list, response);//下载到本地
```
writer_log导出方法如下
```xhtml
/**
* 生成 excel 文件,导出到本地电脑
* @param fname 文件名
* @param list 需要打印的数据,即数据库查询的数据列表
*/
public static void writer_log(HttpServletRequest request,String fname, List list, HttpServletResponse response) {
try {
OutputStream os = response.getOutputStream();//取得输出流
response.reset();//清空输出流
// 下面是对中文文件名的处理 开始
response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式
if(isMsBrowser(request))
fname= java.net.URLEncoder.encode(fname ,"UTF-8");
else fname = new String(fname.getBytes("UTF-8"),"ISO-8859-1");
response.setHeader("Content-Disposition","attachment;filename="+fname+".xls");
response.setContentType("application/msexcel;charset=utf-8");//定义输出类型
// 对中文文件名的处理 结束
// 此处的 Workbook 导入的是 import jxl.Workbook;
WritableWorkbook wbook = Workbook.createWorkbook(os); // 建立excel文件
WritableSheet sheet = wbook.createSheet("系统日志", 0); // 工作表名称
CellView cellView = new CellView();
cellView.setAutosize(true); //设置自动大小
sheet.setColumnView(0, 8); //设置单元格宽度,0是列号,8是宽度
sheet.setColumnView(1, 20); //设置单元格宽度,1是列号,20是宽度
sheet.setColumnView(2, 24);
sheet.setColumnView(3, 20);
sheet.setColumnView(4, 30);
sheet.setColumnView(5, 13);
sheet.setColumnView(6, 15);
sheet.setColumnView(7, 32);
sheet.setColumnView(8, 15);
// 设置Excel字体
WritableFont wfont = new WritableFont(WritableFont.createFont("宋体"), 22,
WritableFont.BOLD, false,
jxl.format.UnderlineStyle.NO_UNDERLINE,
jxl.format.Colour.BLACK); //设置单元格字体样式
WritableCellFormat titleFormat = new WritableCellFormat(wfont); //添加单元格字体
titleFormat.setAlignment(Alignment.CENTRE); //设置文字居中对齐方式;
String[] title = { "系统日志" };
// 设置Excel表头 开始
for (int i = 0; i 原文地址: http://www.cnblogs.com/learnapi/p/8027947.html