1. 程式人生 > >ssh poi匯出匯入Excel

ssh poi匯出匯入Excel

首先需要匯入支援jar包

poi-3.11-20141221.jar 
poi-ooxml-3.11-20141221.jar
poi-ooxml-schemas-3.11-20141221.jar
xmlbeans-2.6.0.jar

user類

資料表user

User.hbmxml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="cn.user.entity.User" table="user">
		<id name="id" type="java.lang.String">
			<column name="id" length="32" />
			<generator class="uuid.hex" />
		</id>
		<property name="name" type="java.lang.String">
			<column name="name" length="20" not-null="true" />
		</property>
		<property name="dept" type="java.lang.String">
			<column name="dept" length="20" not-null="true" />
		</property>		
		<property name="account" type="java.lang.String">
			<column name="account" length="50" not-null="true" />
		</property>
		<property name="password" type="java.lang.String">
			<column name="password" length="50" not-null="true" />
		</property>
		<property name="headImg" type="java.lang.String">
			<column name="headImg" length="100" />
		</property>
		<property name="gender" type="character">
			<column name="gender" length="1" />
		</property>
		<property name="email" type="java.lang.String">
			<column name="email" length="50" />
		</property>
		<property name="mobile" type="java.lang.String">
			<column name="mobile" length="20" />
		</property>
		<property name="birthday" type="java.util.Date">
			<column name="birthday" length="10" />
		</property>
		<property name="state" type="java.lang.String">
			<column name="state" length="1" />
		</property>
		<property name="memo" type="java.lang.String">
			<column name="memo" length="200" />
		</property>
	</class>

</hibernate-mapping>
	

不懂的先來測試瞭解一下excel的用法

import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

 
/*excel基礎元素

工作簿
工作表(屬於工作簿)
行(屬於工作表)
單元格(屬於行;由行和列確定)

-------------操作excel
1、建立/讀取工作簿
2、建立/讀取工作表
3、建立/讀取行
4、建立/讀取單元格


-----------excel樣式

合併單元格物件(CellRangeAddress)屬於工作簿;運用於工作表

CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol) 起始行號,結束行號,起始列號,結束列號


樣式是屬於工作簿的;運用於單元格

字型是屬於工作簿的;加載於樣式;通用樣式運用於單元格*/



public class TestPOI2Eecel {
    //03版本建立工作簿excel設定內容
	@Test
	public void testWrite03() throws Exception{
        //1、建立工作簿
	    HSSFWorkbook workbook=new HSSFWorkbook();   
        //2、建立工作表
	    HSSFSheet sheet=workbook.createSheet("hello word");	    
        //3、建立行 第三行
	    HSSFRow row=sheet.createRow(2);	    
        //4、建立單元格 第三行第三列
	    HSSFCell cell= row.createCell(2);
	    cell.setCellValue("hello word");	    
	    //輸出到硬碟	    
	    FileOutputStream outputStream=   new FileOutputStream("E:\\測試.xls");
	    //把Excel輸出到具體地址	    
	    workbook.write(outputStream);
	    workbook.close();
	    outputStream.close();
	}
	
	//03版本讀取工作簿excel內容
	@Test
    public void testRead03() throws Exception{
        //1、讀取工作簿
	    FileInputStream inputStream= new FileInputStream("E:\\測試.xls");
        HSSFWorkbook workbook=new HSSFWorkbook(inputStream);                
        //2、讀取工作表
        HSSFSheet sheet=workbook.getSheetAt(0);       
        //3、讀取行 第三行
        HSSFRow row=sheet.getRow(2);        
        //4、讀取單元格 第三行第三列
        HSSFCell cell= row.getCell(2);
         System.out.println("03獲取單元格內容:"+cell.getStringCellValue());               
        workbook.close();
        inputStream.close();
    }
	
	
    //07版本建立工作簿excel設定內容
    @Test
    public void testWrite07() throws Exception{
        //1、建立工作簿
        XSSFWorkbook workbook=new XSSFWorkbook();                
        //2、建立工作表
        XSSFSheet sheet=workbook.createSheet("hello word");        
        //3、建立行 第三行
        XSSFRow row=sheet.createRow(2);        
        //4、建立單元格 第三行第三列
        XSSFCell cell= row.createCell(2);
        cell.setCellValue("hello word");        
        //輸出到硬碟        
       FileOutputStream outputStream=   new FileOutputStream("E:\\測試.xlsx");
        //把Excel輸出到具體地址        
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
    }
	
    
    //07版本讀取工作簿excel內容
    @Test
    public void testRead07() throws Exception{
        //1、讀取工作簿
        FileInputStream inputStream= new FileInputStream("E:\\測試.xlsx");
        XSSFWorkbook workbook=new XSSFWorkbook(inputStream);                
        //2、讀取工作表
        XSSFSheet sheet=workbook.getSheetAt(0);      
        //3、讀取行 第三行
        XSSFRow row=sheet.getRow(2);        
        //4、讀取單元格 第三行第三列
        XSSFCell cell= row.getCell(2);
         System.out.println("07獲取單元格內容:"+cell.getStringCellValue());               
        workbook.close();
        inputStream.close();
    }
    
  //03 07版本讀取工作簿excel內容 .xls字尾表示03版本  .xlsx字尾表示07版本
    @Test
    public void testRead03And07() throws Exception{
        //1、讀取工作簿
        String fileName="E:\\測試.xls";        
        //是否是excel ^開始 $結束  ?i 忽略大小寫 xls |xlsx 字尾名  \\.表示最後.
        if (fileName.matches("^.+\\.(?i)((xls)|(xlsx))$"));
        {    //用正則表示式判斷是03版本   
            boolean is03Excel=fileName.matches("^.+\\.(?i)(xls)$");
            FileInputStream inputStream=new FileInputStream(fileName);            
            Workbook workbook=is03Excel? new HSSFWorkbook(inputStream):new XSSFWorkbook(inputStream);           
            //2、讀取工作表
            Sheet sheet=workbook.getSheetAt(0);            
            //3、讀取行 第三行
            Row row=sheet.getRow(2);            
            //4、讀取單元格 第三行第三列
            Cell cell= row.getCell(2);
             System.out.println("第三行第三列獲取單元格內容:"+cell.getStringCellValue());       
             workbook.close();
            inputStream.close();
        }        
    }
    
    //03版本建立工作簿excel設定內容樣式
    @Test
    public void testWriteStyle() throws Exception{
        //1、建立工作簿
        HSSFWorkbook workbook=new HSSFWorkbook();
         //1.1合併單元格 第三行3到5列 應用到工作表     
        CellRangeAddress cellRangeAddress= new CellRangeAddress(2,2,2,4); //起始行號,結束行號,起始列號,結束列號        
        //1.2樣式 應用到單元格
        HSSFCellStyle style=workbook.createCellStyle(); 
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中        
        //1.3建立字型 字型是屬於工作簿的;加載於樣式;通用樣式運用於單元格
        HSSFFont font= workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗字型
        //font.setFontHeight((short)280); //設定字型大小 1/20
        font.setFontHeightInPoints((short)16);
        style.setFont(font);//加載於樣式       
        // 1.4設定單元格背景
        //設定背景模式 SOLID_FOREGROUND 背景以設定前景顏色一樣
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        //設定填充背景顏色
        style.setBottomBorderColor(HSSFColor.YELLOW.index);
        //設定填充前景顏色
        //style.setFillForegroundColor(HSSFColor.YELLOW.index);//黃色背景
        style.setFillForegroundColor(HSSFColor.RED.index);//紅色背景
              
        //2、建立工作表
        HSSFSheet sheet=workbook.createSheet("hello word");
        sheet.addMergedRegion(cellRangeAddress);
        
        //3、建立行 第三行
        HSSFRow row=sheet.createRow(2);        
        //4、建立單元格 第三行第三列
        HSSFCell cell= row.createCell(2);
        cell.setCellStyle(style);
        cell.setCellValue("hello word");        
        //輸出到硬碟        
        FileOutputStream outputStream=   new FileOutputStream("E:\\測試.xls");
        //把Excel輸出到具體地址        
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
    }
    
}

搞懂上面就開始弄匯出匯入

前端頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>使用者管理</title>
    <%@include file="/common/header.jsp" %>
    <script type="text/javascript">
      	//全選、全反選
		function doSelectAll(){
			// jquery 1.6 前
			//$("input[name=selectedRow]").attr("checked", $("#selAll").is(":checked"));
			//prop jquery 1.6+建議使用
			$("input[name=selectedRow]").prop("checked", $("#selAll").is(":checked"));		
		}
      	//新增
      	function doAdd(){
      		document.forms[0].action = "${basePath}nsfw/user_addUI.action";
      		document.forms[0].submit();
      	}
      	//編輯
      	function doEdit(id){
      		document.forms[0].action = "${basePath}nsfw/user_editUI.action?user.id=" + id;
      		document.forms[0].submit();
      	}
      	//刪除
      	function doDelete(id){
      		document.forms[0].action = "${basePath}nsfw/user_delete.action?user.id=" + id;
      		document.forms[0].submit();
      	}
      	//批量刪除
      	function doDeleteAll(){
      		document.forms[0].action = "${basePath}nsfw/user_deleteSelected.action";
      		document.forms[0].submit();
      	}
      	//匯出使用者列表
      	function doExportExcel(){
      		window.open("${basePath}nsfw/user_exportExcel.action");
      	}
      	//匯入
      	function doImportExcel(){
      		document.forms[0].action = "${basePath}nsfw/user_importExcel.action";
      		document.forms[0].submit();
      	}
    </script>
</head>
<body class="rightBody">
<form name="form1" action="" method="post" enctype="multipart/form-data">
    <div class="p_d_1">
        <div class="p_d_1_1">
            <div class="content_info">
                <div class="c_crumbs"><div><b></b><strong>使用者管理</strong></div> </div>
                <div class="search_art">
                    <li>
                        使用者名稱:<s:textfield name="user.name" cssClass="s_text" id="userName"  cssStyle="width:160px;"/>
                    </li>
                    <li><input type="button" class="s_button" value="搜 索" onclick="doSearch()"/></li>
                    <li style="float:right;">
                        <input type="button" value="新增" class="s_button" onclick="doAdd()"/> 
                        <input type="button" value="刪除" class="s_button" onclick="doDeleteAll()"/> 
                        <input type="button" value="匯出" class="s_button" onclick="doExportExcel()"/> 
                    	<input name="userExcel" type="file"/>
                        <input type="button" value="匯入" class="s_button" onclick="doImportExcel()"/> 

                    </li>
                </div>

                <div class="t_list" style="margin:0px; border:0px none;">
                    <table width="100%" border="0">
                        <tr class="t_tit">
                            <td width="30" align="center"><input type="checkbox" id="selAll" onclick="doSelectAll()" /></td>
                            <td width="140" align="center">使用者名稱</td>
                            <td width="140" align="center">帳號</td>
                            <td width="160" align="center">所屬部門</td>
                            <td width="80" align="center">性別</td>
                            <td align="center">電子郵箱</td>
                            <td width="100" align="center">操作</td>
                        </tr>
                        <s:iterator value="userList" status="st">
                            <tr <s:if test="#st.odd">bgcolor="f8f8f8"</s:if> >
                                <td align="center"><input type="checkbox" name="selectedRow" value="<s:property value='id'/>" /></td>
                                <td align="center"><s:property value="name"/></td>
                                <td align="center"><s:property value="account"/></td>
                                <td align="center"><s:property value="dept"/></td>
                                <%-- <td align="center"><s:property value="gender?'男':'女'"/></td> --%>
                                <td align="center"><s:property value="gender"/></td>
                                <td align="center"><s:property value="email"/></td>
                                <td align="center">
                                    <a href="javascript:doEdit('<s:property value='id'/>')">編輯</a>
                                    <a href="javascript:doDelete('<s:property value='id'/>')">刪除</a>
                                </td>
                            </tr>
                        </s:iterator>
                    </table>
                </div>
            </div>
        <div class="c_pate" style="margin-top: 5px;">
		<table width="100%" class="pageDown" border="0" cellspacing="0"
			cellpadding="0">
			<tr>
				<td align="right">
                 	總共1條記錄,當前第 1 頁,共 1 頁   
                            <a href="#">上一頁</a>  <a href="#">下一頁</a>
					到 <input type="text" style="width: 30px;" onkeypress="if(event.keyCode == 13){doGoPage(this.value);}" min="1"
					max="" value="1" />   
			    </td>
			</tr>
		</table>	
        </div>
        </div>
    </div>
</form>
</body>
</html>

接下來寫一個Useraction類

import java.io.File;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import cn.itcast.nsfw.user.entity.User;
import cn.itcast.nsfw.user.service.UserService;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {
	
	@Resource
	private UserService userService;
	private List<User> userList;
	private User user;
	private String[] selectedRow;
	private File headImg;
	private String headImgContentType;
	private String headImgFileName;
	
	private File userExcel;
	private String userExcelContentType;
	private String userExcelFileName;
	

	//列表頁面
	public String listUI(){
		userList = userService.findObjects();
		return "listUI";
	}
	//跳轉到新增頁面
	public String addUI(){
		return "addUI";
	}
	//儲存新增
	public String add(){
		try {
			if(user != null){
				//處理頭像
				if(headImg != null){
					//1、儲存頭像到upload/user
					//獲取儲存路徑的絕對地址
					String filePath = ServletActionContext.getServletContext().getRealPath("upload/user");
					String fileName = UUID.randomUUID().toString().replaceAll("-", "") + headImgFileName.substring(headImgFileName.lastIndexOf("."));
					//複製檔案
					File destFile=new File(filePath, fileName);
					FileUtils.copyFile(headImg, destFile);
					
					//2、設定使用者頭像路徑
					user.setHeadImg("user/" + fileName);
				}
				userService.save(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "list";
	}
	//跳轉到編輯頁面
	public String editUI(){
		if (user != null && user.getId() != null) {
			user = userService.findObjectById(user.getId());
		}
		return "editUI";
	}
	//儲存編輯
	public String edit(){
		try {
			if(user != null){
				//處理頭像
				if(headImg != null){
					//1、儲存頭像到upload/user
					//獲取儲存路徑的絕對地址
					String filePath = ServletActionContext.getServletContext().getRealPath("upload/user");
					String fileName = UUID.randomUUID().toString().replaceAll("-", "") + headImgFileName.substring(headImgFileName.lastIndexOf("."));
					//複製檔案
					File destFile=new File(filePath, fileName);
                    FileUtils.copyFile(headImg, destFile);
					
                    //1.2刪除原來頭像
                    //13獲取原來頭像絕對路徑
                    String oldPath = ServletActionContext.getServletContext().getRealPath("upload");
                    /**
                     * 因為原來路徑為getRealPath("upload/user");但是儲存時候user.setHeadImg("user/" + fileName);已經加了/user 所以上面獲取upload就可以
                     * 
                     * 複製頭像到檔案  相當於到upload/userw資料夾找到原來的頭像 然後刪除
                     */
                    File oldFile=new File(oldPath, user.getHeadImg());
                    //刪除
                    oldFile.delete();
 
					//2、設定使用者頭像路徑
					user.setHeadImg("user/" + fileName);
				}

				userService.update(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "list";
	}
	//刪除
	public String delete(){
		if(user != null && user.getId() != null){
			userService.delete(user.getId());
		}
		return "list";
	}
	//批量刪除
	public String deleteSelected(){
		if(selectedRow != null){
			for(String id: selectedRow){
				userService.delete(id);
			}
		}
		return "list";
	}
	//匯出使用者列表
	public void exportExcel(){
		try {
			//1、查詢使用者列表
			userList = userService.findObjects();
			//2、匯出
			HttpServletResponse response = ServletActionContext.getResponse();
			//告訴瀏覽器匯出為excel檔案型別
			response.setContentType("application/x-execl");
			//設定以瀏覽器開啟方式並且設定檔名以及編碼
			response.setHeader("Content-Disposition", "attachment;filename=" + new String("使用者列表.xls".getBytes(), "ISO-8859-1"));
			//獲取輸出流
			ServletOutputStream outputStream = response.getOutputStream();
			//呼叫匯出方法
			userService.exportExcel(userList, outputStream);
			if(outputStream != null){
				outputStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//匯入使用者列表
	public String importExcel(){
		//1、獲取excel檔案
		if(userExcel != null){
			//是否是excel ^開始 .+任意字串 $結束  ?i 忽略大小寫 xls | xlsx 字尾名  \\.表示最後.
			if(userExcelFileName.matches("^.+\\.(?i)((xls)|(xlsx))$")){
				//2、匯入
				userService.importExcel(userExcel, userExcelFileName);
			}
		}
		return "list";
	}
	
	public List<User> getUserList() {
		return userList;
	}
	public void setUserList(List<User> userList) {
		this.userList = userList;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public String[] getSelectedRow() {
		return selectedRow;
	}
	public void setSelectedRow(String[] selectedRow) {
		this.selectedRow = selectedRow;
	}
	public File getHeadImg() {
		return headImg;
	}
	public void setHeadImg(File headImg) {
		this.headImg = headImg;
	}
	public String getHeadImgContentType() {
		return headImgContentType;
	}
	public void setHeadImgContentType(String headImgContentType) {
		this.headImgContentType = headImgContentType;
	}
	public String getHeadImgFileName() {
		return headImgFileName;
	}
	public void setHeadImgFileName(String headImgFileName) {
		this.headImgFileName = headImgFileName;
	}
	public File getUserExcel() {
		return userExcel;
	}
	public void setUserExcel(File userExcel) {
		this.userExcel = userExcel;
	}
	public String getUserExcelContentType() {
		return userExcelContentType;
	}
	public void setUserExcelContentType(String userExcelContentType) {
		this.userExcelContentType = userExcelContentType;
	}
	public String getUserExcelFileName() {
		return userExcelFileName;
	}
	public void setUserExcelFileName(String userExcelFileName) {
		this.userExcelFileName = userExcelFileName;
	}
	
}

接下來service層 

import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import cn.itcast.core.util.ExcelUtil;
import cn.itcast.nsfw.user.dao.UserDao;
import cn.itcast.nsfw.user.entity.User;
import cn.itcast.nsfw.user.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {
	
	@Resource 
	private UserDao userDao;

	@Override
	public void save(User user) {
		userDao.save(user);
	}

	@Override
	public void update(User user) {
		userDao.update(user);
	}

	@Override
	public void delete(Serializable id) {
		userDao.delete(id);
	}

	@Override
	public User findObjectById(Serializable id) {
		return userDao.findObjectById(id);
	}

	@Override
	public List<User> findObjects() {
		return userDao.findObjects();
	}

	//實現匯出
	public void exportExcel(List<User> userList, ServletOutputStream outputStream) {
		ExcelUtil.exportUserExcel(userList, outputStream);
	}

	//實現匯入
	public void importExcel(File userExcel, String userExcelFileName) {
		try {
			FileInputStream fileInputStream = new FileInputStream(userExcel);
			//正則表示式判斷excel為03版本 ^開始 $結束  ?i 忽略大小寫 xls 字尾名  \\.最後.  03版本字尾為xls 07版本 xlsx
			boolean is03Excel = userExcelFileName.matches("^.+\\.(?i)(xls)$");
			//1、讀取工作簿
			Workbook workbook = is03Excel ? new HSSFWorkbook(fileInputStream):new XSSFWorkbook(fileInputStream);
			//2、讀取工作表
			Sheet sheet = workbook.getSheetAt(0);
			//3、讀取行
			if(sheet.getPhysicalNumberOfRows() > 2){
				User user = null;
				for(int k = 2; k < sheet.getPhysicalNumberOfRows(); k++){
					//4、讀取單元格
					Row row = sheet.getRow(k);
					user = new User();
					//使用者名稱
					Cell cell0 = row.getCell(0);
					user.setName(cell0.getStringCellValue());
					//帳號
					Cell cell1 = row.getCell(1);
					user.setAccount(cell1.getStringCellValue());
					//所屬部門
					Cell cell2 = row.getCell(2);
					user.setDept(cell2.getStringCellValue());
					//性別
					Cell cell3 = row.getCell(3);
					//user.setGender(cell3.getStringCellValue().equals("男"));
					char ch=cell3.getStringCellValue().charAt(0); //將獲取的字串轉為字元
					System.out.println(ch);
					user.setGender(ch);
					//手機號
					String mobile = "";
					Cell cell4 = row.getCell(4);
					try {
						mobile = cell4.getStringCellValue();
					} catch (Exception e) {
						double dMobile = cell4.getNumericCellValue();
						mobile = BigDecimal.valueOf(dMobile).toString();
					}
					user.setMobile(mobile);
					
					//電子郵箱
					Cell cell5 = row.getCell(5);
					user.setEmail(cell5.getStringCellValue());
					//生日
					Cell cell6 = row.getCell(6);
					if(cell6.getDateCellValue() != null){
						user.setBirthday(cell6.getDateCellValue());
					}
					//預設使用者密碼為 123456
					user.setPassword("123456");
					//預設使用者狀態為 有效
					user.setState(User.USER_STATE_VALID);
					
					//5、儲存使用者
					save(user);
				}
			}
			workbook.close();
			fileInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

匯出的方法抽取

package cn.itcast.core.util;

import java.util.List;

import javax.servlet.ServletOutputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;

import cn.itcast.nsfw.user.entity.User;

public class ExcelUtil {

	/**
	 * 匯出使用者的所有列表到excel
	 * @param userList 使用者列表
	 * @param outputStream 輸出流
	 */
	public static void exportUserExcel(List<User> userList, ServletOutputStream outputStream) {
		try {
			//1、建立工作簿
			HSSFWorkbook workbook = new HSSFWorkbook();
			//1.1、建立合併單元格物件
			CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 4);//起始行號,結束行號,起始列號,結束列號
			
			//1.2、頭標題樣式
			HSSFCellStyle style1 = createCellStyle(workbook, (short)16);
			
			//1.3、列標題樣式
			HSSFCellStyle style2 = createCellStyle(workbook, (short)13);
			
			//2、建立工作表
			HSSFSheet sheet = workbook.createSheet("使用者列表");
			//2.1、載入合併單元格物件
			sheet.addMergedRegion(cellRangeAddress);
			//設定預設列寬
			sheet.setDefaultColumnWidth(25);
			
			//3、建立行
			//3.1、建立頭標題行;並且設定頭標題
			HSSFRow row1 = sheet.createRow(0);
			HSSFCell cell1 = row1.createCell(0);
			//載入單元格樣式
			cell1.setCellStyle(style1);
			cell1.setCellValue("使用者列表");
			
			//3.2、建立列標題行;並且設定列標題
			HSSFRow row2 = sheet.createRow(1);
			String[] titles = {"使用者名稱","帳號", "所屬部門", "性別", "電子郵箱"};
			for(int i = 0; i < titles.length; i++){
				HSSFCell cell2 = row2.createCell(i);
				//載入單元格樣式
				cell2.setCellStyle(style2);
				cell2.setCellValue(titles[i]);
			}
			
			//4、操作單元格;將使用者列表寫入excel
			if(userList != null){
				for(int j = 0; j < userList.size(); j++){
					HSSFRow row = sheet.createRow(j+2);//因為前面已經2行了所以要+2
					HSSFCell cell11 = row.createCell(0);
					cell11.setCellValue(userList.get(j).getName());
					HSSFCell cell12 = row.createCell(1);
					cell12.setCellValue(userList.get(j).getAccount());
					HSSFCell cell13 = row.createCell(2);
					cell13.setCellValue(userList.get(j).getDept());
					HSSFCell cell14 = row.createCell(3);
					//cell14.setCellValue(userList.get(j).isGender()?"男":"女");
					System.out.println(userList.get(j).getGender());					
					cell14.setCellValue(String.valueOf(userList.get(j).getGender()));  //注意:要將字元轉為字串
					HSSFCell cell15 = row.createCell(4);
					cell15.setCellValue(userList.get(j).getEmail());
				}
			}
			//5、輸出
			workbook.write(outputStream);
			workbook.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 建立單元格樣式
	 * @param workbook 工作簿
	 * @param fontSize 字型大小
	 * @return 單元格樣式
	 */
	private static HSSFCellStyle createCellStyle(HSSFWorkbook workbook, short fontSize) {
		HSSFCellStyle style = workbook.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
		//建立字型
		HSSFFont font = workbook.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗字型
		font.setFontHeightInPoints(fontSize);
		//載入字型
		style.setFont(font);
		return style;
	}

}

user-struts.xml主要程式碼

<package name="user-action" namespace="/nsfw" extends="struts-default">
		<action name="user_*" class="cn.user.action.UserAction" method="{1}">
			<result name="{1}">/WEB-INF/jsp/nsfw/user/{1}.jsp</result>
			<result name="list" type="redirectAction">
				<param name="actionName">user_listUI</param>
			</result>
			
		</action>
	</package>

要匯入的excel檔案內容

匯入後