Java 使用POI實現execl的導入導出數據實踐

該篇文章使用poi3.5的版本 java

須要導入包以下 web

execl導入 app

/**
	 * execl 數據導入
	 * @author 小塗
	 * @title : import_excel
	 * @date Aug 21, 2013 1:04:42 PM
	 * @return String
	 */
	public static String import_excel(){
		String id=null;
		String name=null;
		String  sex=null;
		String  Dormitory=null;
		String Sept=null;

		Workbook workbook = null;
		int k=0;
		int flag = 0;   //指示指針所訪問的位置
		String path="C:/Users/X/Desktop/212.xls";//獲取文件的路徑
		try {
			InputStream is = new FileInputStream(path);
			HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);

			// 循環工做表Sheet
			for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
				HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
				if (hssfSheet == null) {
					continue;
				}
				// 循環行Row
				for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
					HSSFRow hssfRow = hssfSheet.getRow(rowNum);
					if (hssfRow == null) {
						continue;
					}
					// 循環列Cell
					// "學號","姓名","性別","寢室號","所在系"};
					for (int cellNum = 0; cellNum <=4; cellNum++) {
						HSSFCell xh = hssfRow.getCell(cellNum);
						if (xh == null) {
							continue;
						}
						System.out.print(getValue(xh)+"\t");
					}
					System.out.print("\n");
				}
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return  null;
	}

	
    /**
     * 獲得Excel表中的值
     * 
     * @param hssfCell
     *            Excel中的每個格子
     * @return Excel中每個格子中的值
     */
    @SuppressWarnings("static-access")
    private static String getValue(HSSFCell hssfCell) {
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            // 返回布爾類型的值
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            // 返回數值類型的值
            return String.valueOf(hssfCell.getNumericCellValue());
        } else {
            // 返回字符串類型的值
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }

導出execl 文件 測試

/**
	 * 導出execl 文件
	 * @author 小塗
	 * @title : extport
	 * @date Aug 21, 2013 12:27:38 PM
	 * @return String
	 */

	public String extport(){
		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 {
			out = new FileOutputStream(new File("C:/Users/X/Desktop/212.xls"));
			//response = ServletActionContext.getResponse();//初始化HttpServletResponse對象
	        //out = response.getOutputStream();//
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {

//			 String headerStr ="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;
	}

若是你是在web應用是使用請將Response 和out 的代碼打開 字體

測試結果 指針

導出文件

導入數據 excel

相關文章
相關標籤/搜索