程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> jxl導出Excel文件,jxl導出excel

jxl導出Excel文件,jxl導出excel

編輯:JAVA綜合教程

jxl導出Excel文件,jxl導出excel


一、java項目實現讀取Excel文件和導出Excel文件

實現讀取和導出Excel文件的代碼:

package servlet;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.CellFormat;
import jxl.format.Colour;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class Excel {

	/**
	 * @param args
	 * Excel讀寫程序
	 * @throws IOException 
	 * @throws BiffException 
	 */
	public static void main(String[] args) throws BiffException, IOException {
		//導出Excel文件
		writeExcel();
		//讀取Excel文件
		//readExcel();
	}
	
	//讀Excel文件
	public static void readExcel() throws BiffException, IOException{
		 //創建一個list 用來存儲讀取的內容
		  List list = new ArrayList();
		  Workbook rwb = null;
		  Cell cell = null;
		  
		  //創建輸入流
		  InputStream stream = new FileInputStream("d:\\testJXL.xls");
		  
		  //獲取Excel文件對象
		  rwb = Workbook.getWorkbook(stream);
		  
		  //獲取文件的指定工作表 默認的第一個
		  Sheet sheet = rwb.getSheet(0);  
		 
		  //行數(表頭的目錄不需要,從1開始)
		  for(int i=0; i<sheet.getRows(); i++){
		   
		   //創建一個數組 用來存儲每一列的值
		   String[] str = new String[sheet.getColumns()];
		   
		   //列數
		   for(int j=0; j<sheet.getColumns(); j++){
		   
		    //獲取第i行,第j列的值
		    cell = sheet.getCell(j,i);    
		    str[j] = cell.getContents();
		    
		   }
		   //把剛獲取的列存入list
		   list.add(str);
		  }
		  for(int i=0;i<list.size();i++){
			  String[] str = (String[])list.get(i);
			  for(int j=0;j<str.length;j++){
				  System.out.println(str[j]);
			  }
		  }
		}

	/**
	 * 寫Excel文件
	 */
	public static void writeExcel() {
		String[] title = { "編號", "產品名稱", "產品價格", "產品數量", "生產日期", "產地", "是否出口" };
		try {
			// 獲得開始時間
			long start = System.currentTimeMillis();
			// 輸出的excel的路徑
			String filePath = "e:\\testJXL.xls";
			// 創建Excel工作薄
			WritableWorkbook wwb;
			// 新建立一個jxl文件,即在d盤下生成testJXL.xls
			OutputStream os = new FileOutputStream(filePath);
			wwb = Workbook.createWorkbook(os);
			// 添加第一個工作表並設置第一個Sheet的名字
			WritableSheet sheet = wwb.createSheet("產品清單", 0);
			Label label;
			for (int i = 0; i < title.length; i++) {
				// Label(x,y,z) 代表單元格的第x+1列,第y+1行, 內容z
				// 在Label對象的子對象中指明單元格的位置和內容
				//label = new Label(i, 0, title[i]);
				label = new Label(i, 0, title[i], getHeader());
				// 將定義好的單元格添加到工作表中
				sheet.addCell(label);
			}
			// 下面是填充數據
			/*
			 * 保存數字到單元格,需要使用jxl.write.Number 必須使用其完整路徑,否則會出現錯誤
			 */
			// 填充產品編號
			jxl.write.Number number = new jxl.write.Number(0, 1, 20071001);
			sheet.addCell(number);
			// 填充產品名稱
			label = new Label(1, 1, "金鴿瓜子");
			sheet.addCell(label);
			/*
			 * 定義對於顯示金額的公共格式 jxl會自動實現四捨五入 例如 2.456會被格式化為2.46,2.454會被格式化為2.45
			 */
			jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#,###.00");
			jxl.write.WritableCellFormat wcf = new jxl.write.WritableCellFormat(nf);
			// 填充產品價格
			jxl.write.Number nb = new jxl.write.Number(2, 1, 200000.45, wcf);
			sheet.addCell(nb);
			// 填充產品數量
			jxl.write.Number numb = new jxl.write.Number(3, 1, 200);
			sheet.addCell(numb);
			/*
			 * 定義顯示日期的公共格式 如:yyyy-MM-dd hh:mm
			 */
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String newdate = sdf.format(new Date());
			// 填充出產日期
			label = new Label(4, 1, newdate);
			sheet.addCell(label);
			// 填充產地
			label = new Label(5, 1, "陝西西安");
			sheet.addCell(label);
			/*
			 * 顯示布爾值
			 */
			jxl.write.Boolean bool = new jxl.write.Boolean(6, 1, true);
			sheet.addCell(bool);
			/*
			 * 合並單元格 通過writablesheet.mergeCells(int x,int y,int m,int n);來實現的
			 * 表示將從第x+1列,y+1行到m+1列,n+1行合並
			 */
			sheet.mergeCells(0, 3, 2, 3);
			label = new Label(0, 3, "合並了三個單元格");
			sheet.addCell(label);
			/*
			 * 
			 * 定義公共字體格式 通過獲取一個字體的樣式來作為模板 首先通過web.getSheet(0)獲得第一個sheet
			 * 然後取得第一個sheet的第二列,第一行也就是"產品名稱"的字體
			 */
			CellFormat cf = wwb.getSheet(0).getCell(1, 0).getCellFormat();
			WritableCellFormat wc = new WritableCellFormat();
			// 設置居中
			wc.setAlignment(Alignment.CENTRE);
			// 設置邊框線
			wc.setBorder(Border.ALL, BorderLineStyle.THIN);
			// 設置單元格的背景顏色
			wc.setBackground(jxl.format.Colour.RED);
			label = new Label(1, 5, "字體", wc);
			sheet.addCell(label);

			// 設置字體
			jxl.write.WritableFont wfont = new jxl.write.WritableFont(WritableFont.createFont("隸書"), 20);
			WritableCellFormat font = new WritableCellFormat(wfont);
			label = new Label(2, 6, "隸書", font);
			sheet.addCell(label);

			// 寫入數據
			wwb.write();
			// 關閉文件
			wwb.close();
			long end = System.currentTimeMillis();
			System.out.println("----完成該操作共用的時間是:" + (end - start) / 1000);
		} catch (Exception e) {
			System.out.println("---出現異常---");
			e.printStackTrace();
		}
	}

	/**
	 * 設置頭的樣式
	 * @return
	 */
	public static WritableCellFormat getHeader() {
		WritableCellFormat format = null;
		try {
			WritableFont font = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD);// 定義字體
			font.setColour(Colour.BLUE);// 藍色字體
			format = new WritableCellFormat(font);
			format.setAlignment(jxl.format.Alignment.CENTRE);// 左右居中
			format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 上下居中
			format.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);// 黑色邊框
			format.setBackground(Colour.YELLOW);// 黃色背景
		} catch (WriteException e) {
			e.printStackTrace();
		}
		return format;
	}
}

導出結果:

二、web項目中實現導出Excel文件

2.1、新建動態web項目

新建項目後在項目中添加jxl-2.6.jar文件和servlet-api.jar文件。

2.2、新建數據實體對象Member.java

package entity;

import java.util.Date;
public class Member implements java.io.Serializable {

	// Fields

	private String id;

	private String checkOrg;

	private String sn;

	private String memberName;

	private String sex;

	private String cardId;

	private String duty;

	private String title;

	private String academic;

	private String special;

	private String workTime;

	private String memo;

	private String role;
	
	private Date lastModify;
	
    private Date regTime;

	// Constructors

	/** default constructor */
	public Member() {
	}

	/** full constructor */
	public Member(String checkOrg, String sn, String memberName, String sex,
			String cardId, String duty, String title, String academic,
			String special, String workTime, String memo, String role, Date lastModify, Date regTime) {
		this.checkOrg = checkOrg;
		this.sn = sn;
		this.memberName = memberName;
		this.sex = sex;
		this.cardId = cardId;
		this.duty = duty;
		this.title = title;
		this.academic = academic;
		this.special = special;
		this.workTime = workTime;
		this.memo = memo;
		this.role = role;
		this.lastModify = lastModify;
		this.regTime = regTime;
	}

	// Property accessors

	public String getId() {
		return this.id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getCheckOrg() {
		return this.checkOrg;
	}

	public void setCheckOrg(String checkOrg) {
		this.checkOrg = checkOrg;
	}

	public String getSn() {
		return this.sn;
	}

	public void setSn(String sn) {
		this.sn = sn;
	}

	public String getMemberName() {
		return this.memberName;
	}

	public void setMemberName(String memberName) {
		this.memberName = memberName;
	}

	public String getSex() {
		return this.sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getCardId() {
		return this.cardId;
	}

	public void setCardId(String cardId) {
		this.cardId = cardId;
	}

	public String getDuty() {
		return this.duty;
	}

	public void setDuty(String duty) {
		this.duty = duty;
	}

	public String getTitle() {
		return this.title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getAcademic() {
		return this.academic;
	}

	public void setAcademic(String academic) {
		this.academic = academic;
	}

	public String getSpecial() {
		return this.special;
	}

	public void setSpecial(String special) {
		this.special = special;
	}

	public String getWorkTime() {
		return this.workTime;
	}

	public void setWorkTime(String workTime) {
		this.workTime = workTime;
	}

	public String getMemo() {
		return this.memo;
	}

	public void setMemo(String memo) {
		this.memo = memo;
	}

	public String getRole() {
		return this.role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	public Date getLastModify() {
		return lastModify;
	}

	public void setLastModify(Date lastModify) {
		this.lastModify = lastModify;
	}

	public Date getRegTime() {
		return regTime;
	}

	public void setRegTime(Date regTime) {
		this.regTime = regTime;
	}

}

2.3、添加servlet文件:ExportExlServlet.java

package servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import entity.Member;

public class ExportExlServlet extends HttpServlet {

	private WritableWorkbook wwb = null;

	private WritableSheet sheet = null;

	private WritableSheet sheetk = null;

	private WritableSheet sheeth = null;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String checkOrgId = null;
		String orgName = "XX單位";
		try {
			exportCheckOrgMember(checkOrgId, orgName, response);
		} catch (RowsExceededException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
		exportExcel(response, wwb, orgName + "人員明細表");
	}
	
	/**
	 * 導出數據處理
	 * @param checkOrgId
	 * @param orgName
	 * @param response
	 * @throws IOException
	 * @throws RowsExceededException
	 * @throws WriteException
	 */
	
	private void exportCheckOrgMember(String checkOrgId,String orgName, HttpServletResponse response)
			throws IOException, RowsExceededException, WriteException {
		//此處listMember需要從數據庫中取值
		List<Member> listMember = new ArrayList<Member>();
		Member member1 = new Member("str", "str", "str", "str", "str", "str", "str", "str", "str", "str", "隸書", "str", new Date(), new Date());
		listMember.add(member1);
		listMember.add(member1);
		listMember.add(member1);
		System.out.println(listMember.size()+"***");
		
		
		response.setContentType("application/ms-excel");
		String sheetName_ = orgName + "人員明細表";//文件名==》XX人員明細表
		String sheetName = new String(sheetName_.getBytes(),"iso8859-1");
		  
		response.addHeader("Content-Disposition", "attachment;filename="+ sheetName + ".xls");

		OutputStream os = response.getOutputStream();
		wwb = Workbook.createWorkbook(os);
		wwb.setProtected(false);

		//EXECL中的一個sheet
		sheetk = wwb.createSheet("人員明細", 0);

		//============設置execl表的一些屬性===========
		WritableFont wf = new WritableFont(WritableFont.ARIAL, 13,WritableFont.BOLD, false);
		WritableCellFormat wcf = new WritableCellFormat(wf);
		WritableFont wf1 = new WritableFont(WritableFont.ARIAL, 13,WritableFont.NO_BOLD, false);
		WritableCellFormat wcf1 = new WritableCellFormat(wf1);
		wcf.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
		wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
		wcf1.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
		wcf1.setVerticalAlignment(VerticalAlignment.CENTRE);
		//============設置execl表的一些屬性======END=====
		
		/*sheetk.mergeCells(0, 0, 9, 0);
		sheetk.addCell(new Label(0, 0, "人員明細表《這是合並的單元格》", wcf));
		
		//添加單元格  new Label(列位置,行位置,單元格內容,WritableCellFormat對象)
		//此處第二個參數1,代表第二行,上面合並的單元格是第一行
		sheetk.addCell(new Label(0, 1, "序號", wcf));
		sheetk.addCell(new Label(1, 1, "姓名", wcf));
		sheetk.addCell(new Label(2, 1, "性別", wcf));
		sheetk.addCell(new Label(3, 1, "身份證號", wcf));
		sheetk.addCell(new Label(4, 1, "學歷", wcf));
		sheetk.addCell(new Label(5, 1, "專業", wcf));
		sheetk.addCell(new Label(6, 1, "職稱", wcf));
		sheetk.addCell(new Label(7, 1, "職務", wcf));
		sheetk.addCell(new Label(8, 1, "角色", wcf));
		sheetk.addCell(new Label(9, 1, "備注", wcf));*/
		
		String[] title = {"編號", "姓名", "性別", "身份證號", "學歷", "專業", "職稱", "職務", "角色", "備注"};
		Label label;
		for (int i = 0; i < title.length; i++) {
			// Label(x,y,z) 代表單元格的第x+1列,第y+1行, 內容z
			// 在Label對象的子對象中指明單元格的位置和內容
			//label = new Label(i, 0, title[i]);
			label = new Label(i, 0, title[i], Excel.getHeader());
			// 將定義好的單元格添加到工作表中
			sheetk.addCell(label);
		}
		// 設置字體
					
		jxl.write.WritableFont wfont = new jxl.write.WritableFont(WritableFont.createFont("隸書"), 20);
		WritableCellFormat font = new WritableCellFormat(wfont);
		//循環數據,將數據填充到單元格內
		int t = 1;
		for (Member member:listMember) {
			sheetk.addCell(new Label(0, t, t+"", wcf1));
			sheetk.addCell(new Label(1, t, member.getMemberName(), wcf1));
			sheetk.addCell(new Label(2, t, member.getSex(), wcf1));
			sheetk.addCell(new Label(3, t, member.getCardId(), wcf1));
			sheetk.addCell(new Label(4, t, member.getAcademic(), wcf1));
			sheetk.addCell(new Label(5, t, member.getSpecial(), wcf1));
			sheetk.addCell(new Label(6, t, member.getTitle(), wcf1));
			sheetk.addCell(new Label(7, t, member.getDuty(), wcf1));
			sheetk.addCell(new Label(8, t, member.getRole(), wcf1));
			sheetk.addCell(new Label(9, t, member.getMemo(), font));
			t++;
		}
	}
	
	/*
	 * 執行導出操作
	 */
	private void exportExcel(HttpServletResponse response,
			WritableWorkbook retValue, String filename) {
		response.setContentType("application/ms-excel");
		/*response.addHeader("Content-Disposition", "attachment; filename="
				+ filename + ".xls");*/
		try {
			retValue.write();
			retValue.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
	}
}

2.4、在web.xml文件中添加servlet配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  	<servlet-name>ExportExlServlet</servlet-name>
  	<servlet-class>servlet.ExportExlServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>ExportExlServlet</servlet-name>
  	<url-pattern>/ExportExlServlet</url-pattern>
  </servlet-mapping>
</web-app>

2.5、添加index.jsp請求servlet

<body>
    This is my JSP page. <br>
    <a href="ExportExlServlet">導出數據</a>
  </body>

  導出結果:

 源碼下載地址:https://github.com/ablejava/Jxl-Excel

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved