Java_导出Excel
导出的Excel标题、Sheet名称、数据内容都可以使用中文
一、pom.xml引入jar包
| 1 2 3 4 5 | <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-ooxml</artifactId>            <version>3.13</version>        </dependency> | 
二、Excel操作内部类
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | importorg.apache.poi.hssf.util.HSSFColor;importorg.apache.poi.ss.util.CellRangeAddress;importorg.apache.poi.xssf.usermodel.*;publicclassExportInternalUtil {    privateXSSFWorkbook wb = null;    privateXSSFSheet sheet = null;    /**     * @param wb     * @param sheet     */    publicExportInternalUtil(XSSFWorkbook wb, XSSFSheet sheet) {        this.wb = wb;        this.sheet = sheet;    }    /**     * 合并单元格后给合并后的单元格加边框     *      * @param region     * @param cs     */    publicvoidsetRegionStyle(CellRangeAddress region, XSSFCellStyle cs) {        inttoprowNum = region.getFirstRow();        for(inti = toprowNum; i <= region.getLastRow(); i++) {            XSSFRow row = sheet.getRow(i);            for(intj = region.getFirstColumn(); j <= region.getLastColumn(); j++) {                XSSFCell cell = row.getCell(j);// XSSFCellUtil.getCell(row,                                                // (short) j);                cell.setCellStyle(cs);            }        }    }    /**     * 设置表头的单元格样式     *      * @return     */    publicXSSFCellStyle getHeadStyle() {        // 创建单元格样式        XSSFCellStyle cellStyle = wb.createCellStyle();        // 设置单元格的背景颜色为淡蓝色        cellStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index);        cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);        // 设置单元格居中对齐        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);        // 设置单元格垂直居中对齐        cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);        // 创建单元格内容显示不下时自动换行        cellStyle.setWrapText(true);        // 设置单元格字体样式        XSSFFont font = wb.createFont();        // 设置字体加粗        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);        font.setFontName("宋体");        font.setFontHeight((short) 200);        cellStyle.setFont(font);        // 设置单元格边框为细线条        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);        returncellStyle;    }    /**     * 设置表体的单元格样式     *      * @return     */    publicXSSFCellStyle getBodyStyle() {        // 创建单元格样式        XSSFCellStyle cellStyle = wb.createCellStyle();        // 设置单元格居中对齐        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);        // 设置单元格垂直居中对齐        cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);        // 创建单元格内容显示不下时自动换行        cellStyle.setWrapText(true);        // 设置单元格字体样式        XSSFFont font = wb.createFont();        // 设置字体加粗        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);        font.setFontName("宋体");        font.setFontHeight((short) 200);        cellStyle.setFont(font);        // 设置单元格边框为细线条        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);        returncellStyle;    }} | 
三、Excel操作类
共外部调用,可设置Sheet名称、标题、数据等
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | importjava.io.IOException;importjava.util.ArrayList;importjavax.servlet.ServletOutputStream;importorg.apache.poi.xssf.usermodel.XSSFCell;importorg.apache.poi.xssf.usermodel.XSSFCellStyle;importorg.apache.poi.xssf.usermodel.XSSFRow;importorg.apache.poi.xssf.usermodel.XSSFSheet;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;importcom.james.domain.User;publicclassExportUtil {    publicstaticvoidExportExcel(String[] titles, ArrayList<User> list, ServletOutputStream outputStream) {        // 创建一个workbook 对应一个excel应用文件        XSSFWorkbook workBook = newXSSFWorkbook();        // 在workbook中添加一个sheet,对应Excel文件中的sheet        //Sheet名称,可以自定义中文名称        XSSFSheet sheet = workBook.createSheet("Sheet1");        ExportInternalUtil exportUtil = newExportInternalUtil(workBook, sheet);        XSSFCellStyle headStyle = exportUtil.getHeadStyle();        XSSFCellStyle bodyStyle = exportUtil.getBodyStyle();        // 构建表头        XSSFRow headRow = sheet.createRow(0);        XSSFCell cell = null;        // 输出标题        for(inti = 0; i < titles.length; i++) {            cell = headRow.createCell(i);            cell.setCellStyle(headStyle);            cell.setCellValue(titles[i]);        }        // 构建表体数据        for(intj = 0; j < list.size(); j++) {            XSSFRow bodyRow = sheet.createRow(j + 1);            User user = list.get(j);            cell = bodyRow.createCell(0);            cell.setCellStyle(bodyStyle);            cell.setCellValue(user.getLastIp());            cell = bodyRow.createCell(1);            cell.setCellStyle(bodyStyle);            cell.setCellValue(user.getLastVisit());            cell = bodyRow.createCell(2);            cell.setCellStyle(bodyStyle);            cell.setCellValue(user.getPassword());                        cell = bodyRow.createCell(3);            cell.setCellStyle(bodyStyle);            cell.setCellValue(user.getUserName());                        cell = bodyRow.createCell(4);            cell.setCellStyle(bodyStyle);            cell.setCellValue(user.getUserId());        }        try{            workBook.write(outputStream);            outputStream.flush();            outputStream.close();        } catch(IOException e) {            e.printStackTrace();        } finally{            try{                outputStream.close();            } catch(IOException e) {                e.printStackTrace();            }        }    }} | 
四、SpringMVC Controller层调用
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | @RequestMapping(value = "/excelDownload")    publicString exportExcel(HttpServletResponse response) {        try{            //String fileName = new String(("导出excel标题").getBytes(), "UTF-8") + ".xlsx";            String fileName=newString(("导出excel标题").getBytes("gb2312"), "iso8859-1")+ ".xlsx";            response.setContentType("application/vnd.ms-excel;charset=UTF-8");            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);            response.setCharacterEncoding("utf-8");            // response.setHeader("Content-disposition", "attachment; filename="            // + "exdddcel" + ".xlsx");// 组装附件名称和格式            String[] titles = { "最后IP", "最后访问时间", "密码", "用户名", "用户编号"};            /*SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");            String date = df.format(new Date());            Date dateNow = null;            try {                dateNow = df.parse(date);            } catch (ParseException e) {                e.printStackTrace();            }*/            Date dateNow = newDate();                        ArrayList<User> users = newArrayList<User>();            User user = newUser();            user.setLastIp("127.0.0.1");            user.setLastVisit(dateNow);            user.setPassword("123");            user.setUserId(1);            user.setUserName("名称:James");            users.add(user);            user = newUser();            user.setLastIp("192.0.0.1");            user.setLastVisit(dateNow);            user.setPassword("456");            user.setUserId(2);            user.setUserName("名称:Mary");            users.add(user);            ServletOutputStream outputStream = response.getOutputStream();            ExportUtil.ExportExcel(titles, users, outputStream);        } catch(IOException e) {            e.printStackTrace();        }        returnnull;    } | 
五、程序中用到的实体类User
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | importjava.io.Serializable;importjava.util.Date;publicclassUser implementsSerializable {    privateintuserId;    privateString userName;    privateString password;    privateString lastIp;    privateDate lastVisit;    publicintgetUserId() {        returnuserId;    }    publicvoidsetUserId(intuserId) {        this.userId = userId;    }    publicString getUserName() {        returnuserName;    }    publicvoidsetUserName(String userName) {        this.userName = userName;    }    publicString getPassword() {        returnpassword;    }    publicvoidsetPassword(String password) {        this.password = password;    }    publicString getLastIp() {        returnlastIp;    }    publicvoidsetLastIp(String lastIp) {        this.lastIp = lastIp;    }    publicDate getLastVisit() {        returnlastVisit;    }    publicvoidsetLastVisit(Date lastVisit) {        this.lastVisit = lastVisit;    }} | 
六、异常情况
1、标题乱码(注释代码会出现标题乱码)
| 1 2 | //String fileName = new String(("导出excel标题").getBytes(), "UTF-8") + ".xlsx";            String fileName=newString(("导出excel标题").getBytes("gb2312"), "iso8859-1")+ ".xlsx"; | 
七、参考文档
1、http://webook-java.iteye.com/blog/1699621
2、http://www.cnblogs.com/yjmyzz/p/4206463.html
Java_导出Excel的更多相关文章
- C#使用Aspose.Cells导出Excel简单实现
		首先,需要添加引用Aspose.Cells.dll,官网下载地址:http://downloads.aspose.com/cells/net 将DataTable导出Xlsx格式的文件下载(网页输出) ... 
- 利用poi导出Excel
		import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.r ... 
- [django]数据导出excel升级强化版(很强大!)
		不多说了,原理采用xlwt导出excel文件,所谓的强化版指的是实现在网页上选择一定条件导出对应的数据 之前我的博文出过这类文章,但只是实现导出数据,这次左思右想,再加上网上的搜索,终于找出方法实现条 ... 
- NPOI导出Excel
		using System;using System.Collections.Generic;using System.Linq;using System.Text;#region NPOIusing ... 
- ASP.NET Core 导入导出Excel xlsx 文件
		ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ... 
- asp.net DataTable导出Excel 自定义列名
		1.添加引用NPOI.dll 2.cs文件头部添加 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.IO; 3.代码如 ... 
- Aspose.Cells导出Excel(1)
		利用Aspose.Cells导出excel 注意的问题 1.DataTable的处理 2.进行编码,便于中文名文件下载 3.别忘了Aspose.Cells.dll(可以自己在网上搜索) public ... 
- 前端导出Excel兼容写法
		今天整理出在Web前端导出Excel的写法,写了一个工具类,对各个浏览器进行了兼容. 首先,导出的数据来源可能有两种: 1. 页面的HTML内容(一般是table) 2. 纯数据 PS:不同的数据源, ... 
- JS导出excel 兼容ie、chrome、firefox
		运用js实现将页面中的table导出为excel文件,页面显示如下: 导出的excel文件显示如下: 实现代码: <!DOCTYPE html> <html> <head ... 
随机推荐
- 【SCOI2010】维护序列
			NOI2017的简化版…… 就是维护的时候要想清楚怎么讨论. #include<bits/stdc++.h> #define lson (o<<1) #define rson ... 
- gunicorn 启动无日志
			gunicorn -c gunicorn_info.py info:app 接手整理老项目,发现有个服务迁移后启动不了,也没报错信息 修改gunicorn_info.py里的daemon = not ... 
- 属性名、变量名与 内部关键字 重名 加&
			procedure TForm4.btn3Click(Sender: TObject); var MyQj: TQJson; MyPrinter: TPrinter; begin MyQj := TQ ... 
- DateTimeToUnix/UnixToDateTime 对接时间转换
			问题,通过毫秒数来解析出时间:(很多对接的时候经常需要用到) <?php $MyJson = '{"jingdong_vas_subscribe_get_responce": ... 
- grid+report 怎么在项目中使用
			grid+report 的例子很丰富,首先看你所用对应编程语言的例子.参考帮助的“产品介绍->快速入门指导”部分.根据快速入门指导中的说明,先把例子程序运行. 例子分两部分:1.报表模板例子,主 ... 
- Jmeter-----随机生成手机号后8位并去重,来进行注册手机号的压测
			要求:对注册接口进行100000次压测,手机号已126开头,后面的8位数不限 前言:在进行测试中,我们需要对注册接口进行压测100000次,那么就要求手机号码每次填写的不一致,否则手机号使用一次后会出 ... 
- netbeans 开启调试
			在URL中加入一个参数 XDEBUG_SESSION_START=netbeans-xdebug 
- LOJ #6284. 数列分块入门 8-分块(区间查询等于一个数c的元素,并将这个区间的所有元素改为c)
			#6284. 数列分块入门 8 内存限制:256 MiB时间限制:500 ms标准输入输出 题目类型:传统评测方式:文本比较 上传者: hzwer 提交提交记录统计测试数据讨论 2 题目描述 给出 ... 
- Oracle 使用序列、触发器实现自增
			之前项目开发多用mysql,对于id自增长设置,只需要简单修改列属性便好.最近改用ORACLE,头大一圈.ORACLE的相关操作,多用脚本.想短平快,难.最终用sql developer通过UI进行修 ... 
- AndroidManifest.xml文件详解(uses-permission)
			语法(SYNTAX): <uses-permissionandroid:name="string"/> 被包含于(CONTAINED IN): <manifest ... 
