POI的下載與安裝
請到網站http://www.apache.org/dyn/closer.cgi/poi/右擊超鏈接2.5.1.zip下載壓縮包poi-bin-2.5.1-final-20040804.zip(或下載最新的這種壓縮包),解壓縮后得到如圖2.1所示的目錄結構。我們主要用到poi-2.5.1-final-20040804.jar這個庫文件。請把poi-2.5.1-final-20040804.jar這個文件的路徑添加到系統環境變量classpath中,否則無法編譯下面的示例程序。
1. 首先搭建ssh框架(這兒不做介紹);
2. 導入jar包(如下):
3. 導出:(下面以一個例子的形式)
1. 新創建一個jsp頁面如(export.jsp),在頁面上添加如下代碼:
<a href="<%=path %>/indexAction!export.action">導出數據到excel</a>
2. 進入indexAction.java文件,編寫export方法由於要用到一個STUDENT類,就先編寫STUDENT類,Student類代碼如下:
public class Student { private String studentId; private String studentName; private String studentSex; private String studentDormitory; private String studentSept; public String getStudentId() { return studentId; } public void setStudentId(String studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getStudentSex() { return studentSex; } public void setStudentSex(String studentSex) { this.studentSex = studentSex; } public String getStudentDormitory() { return studentDormitory; } public void setStudentDormitory(String studentDormitory) { this.studentDormitory = studentDormitory; } public String getStudentSept() { return studentSept; } public void setStudentSept(String studentSept) { this.studentSept = studentSept; } }
編寫export方法:代碼如下
此類中需要導入的jar包如下:
import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.servlet.http.HttpServletResponse; 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.HSSFHeader; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.struts2.ServletActionContext; public String export()throws Exception { List studentList=new ArrayList<Student>();//學生LIst for(int i=0;i<10;i++) { Student student=new Student();//學生對象 student.setStudentId("200908110"+i); student.setStudentName("楊波"+i); student.setStudentSex("男"); student.setStudentDormitory("14-20"+i); student.setStudentSept("軟件工程系"); studentList.add(student); } String []tableHeader={"學號","姓名","性別","寢室號","所在系"}; short cellNumber=(short)tableHeader.length;//表的列數 HSSFWorkbook workbook = new HSSFWorkbook(); //創建一個excel HSSFCell cell = null; //Excel的列 HSSFRow row = null; //Excel的行 HSSFCellStyle style = workbook.createCellStyle(); //設置表頭的類型 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); HSSFCellStyle style1 = workbook.createCellStyle(); //設置數據類型 style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); HSSFFont font = workbook.createFont(); //設置字體 HSSFSheet sheet = workbook.createSheet("sheet1"); //創建一個sheet HSSFHeader header = sheet.getHeader();//設置sheet的頭 try { if(studentList.size() < 1 ){ header.setCenter("查無資料"); }else{ header.setCenter("學生表"); row = sheet.createRow(0); row.setHeight((short)400); for(int k = 0;k < cellNumber;k++){ cell = row.createCell(k);//創建第0行第k列 cell.setCellValue(tableHeader[k]);//設置第0行第k列的值 sheet.setColumnWidth(k,8000);//設置列的寬度 font.setColor(HSSFFont.COLOR_NORMAL); // 設置單元格字體的顏色. font.setFontHeight((short)350); //設置單元字體高度 style1.setFont(font);//設置字體風格 cell.setCellStyle(style1); } for(int i = 0 ;i < studentList.size() ;i++){ Student student1 = (Student)studentList.get(i);//獲取student對象 row = sheet.createRow((short) (i + 1));//創建第i+1行 row.setHeight((short)400);//設置行高 if(student1.getStudentId() != null){ cell = row.createCell(0);//創建第i+1行第0列 cell.setCellValue(student1.getStudentId());//設置第i+1行第0列的值 cell.setCellStyle(style);//設置風格 } if(student1.getStudentName() != null){ cell = row.createCell(1); //創建第i+1行第1列 cell.setCellValue(student1.getStudentName());//設置第i+1行第1列的值 cell.setCellStyle(style); //設置風格 } //由於下面的和上面的基本相同,就不加注釋了 if(student1.getStudentSex() != null){ cell = row.createCell(2); cell.setCellValue(student1.getStudentSex()); cell.setCellStyle(style); } if(student1.getStudentDormitory()!= null){ cell = row.createCell(3); cell.setCellValue(student1.getStudentDormitory()); cell.setCellStyle(style); } if(student1.getStudentSept() != null){ cell = row.createCell(4); cell.setCellValue(student1.getStudentSept()); cell.setCellStyle(style); } } } } catch (Exception e) { e.printStackTrace(); } HttpServletResponse response = null;//創建一個HttpServletResponse對象 OutputStream out = null;//創建一個輸出流對象 try { response = ServletActionContext.getResponse();//初始化HttpServletResponse對象 out = response.getOutputStream();// StringheaderStr ="student學生"; headerStr =new String(headerStr.getBytes("gb2312"), "ISO8859-1");//headerString為中文時轉碼 response.setHeader("Content-disposition","attachment; filename="+ headerStr+".xls");//filename是下載的xls的名,建議最好用英文 response.setContentType("application/msexcel;charset=UTF-8");//設置類型 response.setHeader("Pragma","No-cache");//設置頭 response.setHeader("Cache-Control","no-cache");//設置頭 response.setDateHeader("Expires", 0);//設置日期頭 workbook.write(out); out.flush(); workbook.write(out); } catch (IOException e) { e.printStackTrace(); }finally{ try{ if(out!=null){ out.close(); } }catch(IOException e){ e.printStackTrace(); } } return null; } 注:最好返回null,否則有可能報錯。
4.數據的導入(以例子的形式展示)
1.jsp頁面的編寫:在頁面上添加如下代碼
其中action可以自己編寫,table標簽的內容可以不要。(DEMO頁面添加TABLE標簽主要是展示導入效果)
<s:form action="indexAction!importExcel.action" method="post" enctype="multipart/form-data" theme="simple"> <td> <s:file name="excelFile" id="excelFile" cssStyle="width:160px"></s:file>//選擇導入的文件 </td> <td> <input type="submit" value="導入學生數據"/> </td> </s:form> //下面是展示導入效果 <table> <th>學號</th><th>姓名</th><th>性別</th><th>寢室號</th><th>所在系</th> <s:iterator value="stuList"> <tr> <td> <s:property value="studentId"/> </td> <td> <s:property value="studentName"/> </td> <td> <s:property value="studentSex"/> </td> <td> <s:property value="studentDormitory"/> </td> <td> <s:property value="studentSept"/> </td> </tr> </s:iterator> </table>
2.strus.xml編寫(如果要展示效果,DEMo就編寫的返回的頁面如下)
<action name="indexAction" class="com.dev.iex.action.IndexAction">
<result name="SUCCESS">/index.jsp</result>
</action>
3. java代碼如下
在indexAction中添加
Import的類:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; 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.HSSFHeader; 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.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.apache.struts2.ServletActionContext; import com.dev.iex.po.Student; 定義的的變量: private File excelFile;//File對象,目的是獲取頁面上傳的文件 private List<Student> stuList=new ArrayList<Student>(); 定義的方法: public File getExcelFile() { return excelFile; } public void setExcelFile(File excelFile) { this.excelFile = excelFile; } public List<Student> getStuList() { return stuList; } public void setStuList(List<Student> stuList) { this.stuList = stuList; } 主要編寫的是importExcel方法,如下: @SuppressWarnings("finally") public String importExcel()throws Exception { String id=null; String name=null; String sex=null; String Dormitory=null; String Sept=null; Workbook workbook = null; int k=0; int flag = 0; //指示指針所訪問的位置 if(excelFile!=null) { String path=excelFile.getAbsolutePath();//獲取文件的路徑 try { workbook = new XSSFWorkbook(path);//初始化workbook對象 for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) { //讀取每一個sheet System.out.println("2007版進入讀取sheet的循環"); if (null != workbook.getSheetAt(numSheets)) { XSSFSheet aSheet = (XSSFSheet)workbook.getSheetAt(numSheets);//定義Sheet對象 for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet.getLastRowNum(); rowNumOfSheet++) { //進入當前sheet的行的循環 if (null != aSheet.getRow(rowNumOfSheet)) { XSSFRow aRow = aSheet.getRow(rowNumOfSheet); //定義行,並賦值 for (int cellNumOfRow = 0; cellNumOfRow <= aRow.getLastCellNum(); cellNumOfRow++) { //讀取rowNumOfSheet值所對應行的數據 XSSFCell xCell = aRow.getCell(cellNumOfRow); //獲得行的列數 //獲得列值 //System.out.println("type="+xCell.getCellType()); if (null != aRow.getCell(cellNumOfRow)) { if(rowNumOfSheet == 0) { // 如果rowNumOfSheet的值為0,則讀取表頭,判斷excel的格式和預定格式是否相符 if(xCell.getCellType() == XSSFCell .CELL_TYPE_NUMERIC) { }else if(xCell.getCellType() == XSSFCell .CELL_TYPE_BOOLEAN) { }else if(xCell.getCellType() == XSSFCell .CELL_TYPE_STRING) { if(cellNumOfRow == 0) { if(xCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim().equals("學號")) { flag++; }else{ System.out.println("錯誤:第一行的學號不符合約定格式"); } }else if(cellNumOfRow == 1) { if(xCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim().equals("姓名")) { flag++; }else{ System.out.println("錯誤:第一行的姓名不符合約定格式"); } }else if(cellNumOfRow == 2) { if(xCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim().equals("性別")){ flag++; }else{ System.out.println("第一行的性別不符合約定格式"); } }else if (cellNumOfRow == 3) { if(xCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim().equals("寢室號")) { flag++; System.out.println("=========flag:" + flag); }else{ System.out.println("第一行的寢室號不符合約定格式"); } }else if (cellNumOfRow == 4) { if(xCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim().equals("所在系")){ flag++; System.out.println("=========flag:" + flag); }else{ System.out.println("第一行的所在系不符合約定格式"); } } } } else { //rowNumOfSheet != 0 即開始打印內容 if(id != null && name != null && sex != null && Dormitory != null && Sept != null ){ Student stu=new Student(); stu.setStudentId(id); stu.setStudentName(name); stu.setStudentSept(Sept); stu.setStudentSex(sex); stu.setStudentDormitory(Dormitory); stuList.add(stu); k++; } } //獲得一行,即讀取每一行 } //讀取每一個sheet } }catch (Exception e) { /******************************************** 下面使用的是2003除了workbook的賦值不同其它與2007基本相同,就不作介紹了 ********************************************* InputStream is = new FileInputStream(path); workbook = new HSSFWorkbook(is); try { for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) { //讀取每一個sheet System.out.println("2003版進入讀取sheet的循環"); if (null != workbook.getSheetAt(numSheets)) { HSSFSheet aSheet = (HSSFSheet)workbook.getSheetAt(numSheets); for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet.getLastRowNum(); rowNumOfSheet++) { //獲得一行 if (null != aSheet.getRow(rowNumOfSheet)) { HSSFRow aRow = aSheet.getRow(rowNumOfSheet); for (int cellNumOfRow = 0; cellNumOfRow <= aRow.getLastCellNum(); cellNumOfRow++) { //讀取rowNumOfSheet值所對應行的數據 HSSFCell aCell = aRow.getCell(cellNumOfRow); //獲得列值 if (null != aRow.getCell(cellNumOfRow)){ if(rowNumOfSheet == 0){ // 如果rowNumOfSheet的值為0,則讀取表頭,判斷excel的格式和預定格式是否相符 if(aCell.getCellType() == HSSFCell .CELL_TYPE_NUMERIC){ }else if(aCell.getCellType() == HSSFCell .CELL_TYPE_BOOLEAN){ }else if(aCell.getCellType() == HSSFCell .CELL_TYPE_STRING){ if(cellNumOfRow == 0){ if(aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim().equals("學號")){ flag++; System.out.println("=========flag:" + flag); }else{ System.out.println("錯誤:第一行的學號不符合約定格式"); } }else if(cellNumOfRow == 1){ if(aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim().equals("姓名")){ flag++; System.out.println("=========flag:" + flag); }else{ System.out.println("錯誤:第一行的姓名不符合約定格式"); } }else if(cellNumOfRow == 2){ if(aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim().equals("性別")){ flag++; System.out.println("=========flag:" + flag); }else{ System.out.println("第一行的性別不符合約定格式"); } }else if (cellNumOfRow == 3){ if(aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim().equals("寢室號")){ flag++; System.out.println("=========flag:" + flag); }else{ System.out.println("第一行的寢室號不符合約定格式"); } }else if (cellNumOfRow == 4){ if(aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim().equals("所在系")){ flag++; System.out.println("=========flag:" + flag); }else{ System.out.println("第一行的所在系不符合約定格式"); } } } } else { if(aCell.getCellType() == HSSFCell .CELL_TYPE_NUMERIC){ //為數值型 System.out.println("======進入XSSFCell .CELL_TYPE_NUMERIC模塊=========="); if(cellNumOfRow == 0){ id = String.valueOf(aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim()); if(id == null){ System.out.println("錯誤:在Sheet"+(numSheets+1)+"中的第"+(rowNumOfSheet+1)+"行的第"+(cellNumOfRow+1)+"列的學號不能為空"); } }else if(cellNumOfRow == 1){ name = String.valueOf(aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim()); if(name == null){ System.out.println("錯誤:在Sheet"+(numSheets+1)+"中的第"+(rowNumOfSheet+1)+"行的第"+(cellNumOfRow+1)+"列的姓名不能為空"); } }else if(cellNumOfRow == 2){ sex = String.valueOf(aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim()); if(sex == null){ System.out.println("錯誤:在Sheet"+(numSheets+1)+"中的第"+(rowNumOfSheet+1)+"行的第"+(cellNumOfRow+1)+"列的性別不能為空"); } }else if (cellNumOfRow == 3){ Dormitory = String.valueOf(aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim()); if(Dormitory == null){ System.out.println("錯誤:在Sheet"+(numSheets+1)+"中的第"+(rowNumOfSheet+1)+"行的第"+(cellNumOfRow+1)+"列的寢室號不能為空"); } }else if (cellNumOfRow == 4){ Sept = String.valueOf(aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim()); if(Sept == null){ System.out.println("錯誤:在Sheet"+(numSheets+1)+"中的第"+(rowNumOfSheet+1)+"行的第"+(cellNumOfRow+1)+"列的所在系不能為空"); } } }else if(aCell.getCellType() == HSSFCell .CELL_TYPE_STRING){ //為字符串型 System.out.print("===============進入XSSFCell .CELL_TYPE_STRING模塊============"); if(cellNumOfRow == 0){ id = aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim(); if(id == null){ System.out.println("錯誤:在Sheet"+(numSheets+1)+"中的第"+(rowNumOfSheet+1)+"行的第"+(cellNumOfRow+1)+"列的學號不能為空"); } }else if(cellNumOfRow == 1){ name = aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim(); if(name == null){ System.out.println("錯誤:在Sheet"+(numSheets+1)+"中的第"+(rowNumOfSheet+1)+"行的第"+(cellNumOfRow+1)+"列的姓名不能為空"); } }else if(cellNumOfRow == 2){ sex = aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim(); if(sex == null){ System.out.println("錯誤:在Sheet"+(numSheets+1)+"中的第"+(rowNumOfSheet+1)+"行的第"+(cellNumOfRow+1)+"列的性別不能為空"); } }else if (cellNumOfRow == 3){ Dormitory =aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim(); if(Dormitory == null){ System.out.println("錯誤:在Sheet"+(numSheets+1)+"中的第"+(rowNumOfSheet+1)+"行的第"+(cellNumOfRow+1)+"列的寢室號不能為空"); } }else if (cellNumOfRow == 4){ Sept =aCell.getStringCellValue().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').trim(); if(Sept == null){ System.out.println("錯誤:在Sheet"+(numSheets+1)+"中的第"+(rowNumOfSheet+1)+"行的第"+(cellNumOfRow+1)+"列的所在系不能為空"); } } }else if (aCell.getCellType() == HSSFCell .CELL_TYPE_BLANK) { System.out.println("提示:在Sheet"+(numSheets+1)+"中的第"+(rowNumOfSheet+1)+"行的第"+(cellNumOfRow+1)+"列的值為空,請查看核對是否符合約定要求".toString()); } } } } if (flag!=5){ System.out.println("請核對后重試"); } } if(id != null && name != null && sex != null && Dormitory != null && Sept != null ){ Student stu=new Student(); stu.setStudentId(id); stu.setStudentName(name); stu.setStudentSept(Sept); stu.setStudentSex(sex); stu.setStudentDormitory(Dormitory); stuList.add(stu); k++; } } if(k!=0){ System.out.println("提示:您導入的數據已存在於數據庫,請核對!k 為:" + k); }else{ System.out.println("提示:成功導入了"+k+"條數據"); } } } } catch (Exception ex) { ex.printStackTrace(); }finally{ try { if(is!=null) is.close(); }catch (Exception e1) { e1.printStackTrace(); } } } } return "SUCCESS"; }