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
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









免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM