导出的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
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
 
public class ExportInternalUtil {
    private XSSFWorkbook wb = null;
 
    private XSSFSheet sheet = null;
 
    /**
     * @param wb
     * @param sheet
     */
    public ExportInternalUtil(XSSFWorkbook wb, XSSFSheet sheet) {
        this.wb = wb;
        this.sheet = sheet;
    }
 
    /**
     * 合并单元格后给合并后的单元格加边框
     *
     * @param region
     * @param cs
     */
    public void setRegionStyle(CellRangeAddress region, XSSFCellStyle cs) {
 
        int toprowNum = region.getFirstRow();
        for (int i = toprowNum; i <= region.getLastRow(); i++) {
            XSSFRow row = sheet.getRow(i);
            for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {
                XSSFCell cell = row.getCell(j);// XSSFCellUtil.getCell(row,
                                                // (short) j);
                cell.setCellStyle(cs);
            }
        }
    }
 
    /**
     * 设置表头的单元格样式
     *
     * @return
     */
    public XSSFCellStyle 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);
        return cellStyle;
    }
 
    /**
     * 设置表体的单元格样式
     *
     * @return
     */
    public XSSFCellStyle 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);
        return cellStyle;
    }
}

三、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
import java.io.IOException;
import java.util.ArrayList;
 
import javax.servlet.ServletOutputStream;
 
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
import com.james.domain.User;
 
public class ExportUtil {
 
    public static void ExportExcel(String[] titles, ArrayList<User> list, ServletOutputStream outputStream) {
        // 创建一个workbook 对应一个excel应用文件
        XSSFWorkbook workBook = new XSSFWorkbook();
        // 在workbook中添加一个sheet,对应Excel文件中的sheet
        //Sheet名称,可以自定义中文名称
        XSSFSheet sheet = workBook.createSheet("Sheet1");
        ExportInternalUtil exportUtil = new ExportInternalUtil(workBook, sheet);
        XSSFCellStyle headStyle = exportUtil.getHeadStyle();
        XSSFCellStyle bodyStyle = exportUtil.getBodyStyle();
        // 构建表头
        XSSFRow headRow = sheet.createRow(0);
        XSSFCell cell = null;
 
        // 输出标题
        for (int i = 0; i < titles.length; i++) {
            cell = headRow.createCell(i);
            cell.setCellStyle(headStyle);
            cell.setCellValue(titles[i]);
        }
        // 构建表体数据
        for (int j = 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")
    public String exportExcel(HttpServletResponse response) {
        try {
            //String fileName = new String(("导出excel标题").getBytes(), "UTF-8") + ".xlsx";
            String fileName=new String(("导出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 = new Date();
             
            ArrayList<User> users = new ArrayList<User>();
            User user = new User();
            user.setLastIp("127.0.0.1");
            user.setLastVisit(dateNow);
            user.setPassword("123");
            user.setUserId(1);
            user.setUserName("名称:James");
            users.add(user);
 
            user = new User();
            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();
        }
        return null;
    }

五、程序中用到的实体类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
import java.io.Serializable;
import java.util.Date;
 
public class User implements Serializable {
    private int userId;
 
    private String userName;
 
    private String password;
 
    private String lastIp;
 
    private Date lastVisit;
 
    public int getUserId() {
        return userId;
    }
 
    public void setUserId(int userId) {
        this.userId = userId;
    }
 
    public String getUserName() {
        return userName;
    }
 
    public void setUserName(String userName) {
        this.userName = userName;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    public String getLastIp() {
        return lastIp;
    }
 
    public void setLastIp(String lastIp) {
        this.lastIp = lastIp;
    }
 
    public Date getLastVisit() {
        return lastVisit;
    }
 
    public void setLastVisit(Date lastVisit) {
        this.lastVisit = lastVisit;
    }
}

六、异常情况

1、标题乱码(注释代码会出现标题乱码)

1
2
//String fileName = new String(("导出excel标题").getBytes(), "UTF-8") + ".xlsx";
            String fileName=new String(("导出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的更多相关文章

  1. C#使用Aspose.Cells导出Excel简单实现

    首先,需要添加引用Aspose.Cells.dll,官网下载地址:http://downloads.aspose.com/cells/net 将DataTable导出Xlsx格式的文件下载(网页输出) ...

  2. 利用poi导出Excel

    import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.r ...

  3. [django]数据导出excel升级强化版(很强大!)

    不多说了,原理采用xlwt导出excel文件,所谓的强化版指的是实现在网页上选择一定条件导出对应的数据 之前我的博文出过这类文章,但只是实现导出数据,这次左思右想,再加上网上的搜索,终于找出方法实现条 ...

  4. NPOI导出Excel

    using System;using System.Collections.Generic;using System.Linq;using System.Text;#region NPOIusing ...

  5. ASP.NET Core 导入导出Excel xlsx 文件

    ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...

  6. asp.net DataTable导出Excel 自定义列名

    1.添加引用NPOI.dll 2.cs文件头部添加 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.IO; 3.代码如 ...

  7. Aspose.Cells导出Excel(1)

    利用Aspose.Cells导出excel 注意的问题 1.DataTable的处理 2.进行编码,便于中文名文件下载 3.别忘了Aspose.Cells.dll(可以自己在网上搜索) public ...

  8. 前端导出Excel兼容写法

    今天整理出在Web前端导出Excel的写法,写了一个工具类,对各个浏览器进行了兼容. 首先,导出的数据来源可能有两种: 1. 页面的HTML内容(一般是table) 2. 纯数据 PS:不同的数据源, ...

  9. JS导出excel 兼容ie、chrome、firefox

    运用js实现将页面中的table导出为excel文件,页面显示如下: 导出的excel文件显示如下: 实现代码: <!DOCTYPE html> <html> <head ...

随机推荐

  1. mac 使用清除废纸篓或彻底删除某文件 附加: smb afp ftp NAS 访问服务器相关

    mac 使用清除废纸篓或彻底删除某文件 附加: smb afp ftp NAS 访问服务器相关 mac 下删除文件方法: 1.使用 cleanmymac  使用 cleamymac 的清理  和 逐个 ...

  2. VMware无法识别USB设备

    VMware虚拟机开始还能识别USB设备/U盘,突然就不行了,在网上找了好久,提供的方法大致如下: 1.   首先Ctrl+R启动运行,输入services.msc,找到一个VMware USB dr ...

  3. 关于springMVC转换json出现的异常

    jackson-core-asl-1.9.0.jar,jackson-mapper-asl-1.9.0.jar两个包 并且在controller中有如下代码 @RequestMapping(value ...

  4. POJ-2563

    Pick-up sticks Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 10364   Accepted: 3842 D ...

  5. GZIP压缩占用CPU大吗?

    http://blog.csdn.net/hguisu/article/details/7793038 Filter之——GZIP全站压缩 http://www.cnblogs.com/jbelial ...

  6. PHP需要学习成长路径

    第一阶段:基础阶段(基础PHP程序员) 重点:把LNMP搞熟练(核心是安装配置基本操作) 目标:能够完成基本的LNMP系统安装,简单配置维护;能够做基本的简单系统的PHP开发;能够在PHP中型系统中支 ...

  7. CentOS7英文环境下使用中文输入法

    一般我们使用英文环境是没有办法使用中文的,这是因为我们没有设置在英文环境下的中文配置,下面我们在英文环境下配置中文输入法ibus使得我们可以输入中文. 首先,安装ibus(centos6以后已经默认安 ...

  8. python打印所有汉字

    n=0 for ch in xrange(0x4e00, 0x9fa6): print unichr(ch), n = n+1 if(n%50==0): print '\n' print n

  9. VMware8安装配置Win7、CentOS-7向导

    1.宿主电脑配置情况 Windows 8.1 中文版 Intel(R) Core(TM) i5-4210U CPU @ 1.70GHz 2.4GHz RAM: 8G Type: 64 bit 2.软件 ...

  10. HRBUST 1313 火影忍者之~静音

    优先队列. 每次将$n$个人压入优先队列,取出$5$个,最后排序. #include<cstdio> #include<cstring> #include<cmath&g ...