`

Jxl导入Excel数据

    博客分类:
  • jxl
阅读更多
Java代码 复制代码
  1. package com.pjb.sys.util;   
  2.   
  3. import java.io.File;   
  4. import java.io.InputStream;   
  5. import java.util.ArrayList;   
  6.   
  7. import jxl.Cell;   
  8. import jxl.Sheet;   
  9. import jxl.Workbook;   
  10. import jxl.write.Label;   
  11. import jxl.write.WritableSheet;   
  12. import jxl.write.WritableWorkbook;   
  13.   
  14. /**  
  15.  * 提供对XLS格式类型的文件进行处理  
  16.  *   
  17.  * @author Administrator  
  18.  *   
  19.  */  
  20. public class XlsTools {   
  21.     private Workbook readBook;   
  22.   
  23.     private int currIndex;   
  24.   
  25.     private ArrayList<String> alLineContent;   
  26.   
  27.     private Cell cell;   
  28.   
  29.     private int firstDataCount;   
  30.   
  31.     private boolean isFirst;   
  32.   
  33.     private Sheet sheet;   
  34.   
  35.     private WritableWorkbook writeBook;   
  36.   
  37.     private WritableSheet writeSheet;   
  38.   
  39.     private Label label;   
  40.   
  41.     /**  
  42.      * 初始化xls文件的读取参数  
  43.      *   
  44.      * @param filePath  
  45.      *            xls文件路径  
  46.      *   
  47.      */  
  48.     public void read(String filePath) throws Exception {   
  49.         try {   
  50.             // 创建xls工作表对象   
  51.             readBook = Workbook.getWorkbook(new File(filePath));   
  52.             // 只读取第一个工作表中的内容   
  53.             sheet = readBook.getSheet(0);   
  54.             currIndex = 0;   
  55.             isFirst = true;   
  56.         } catch (Exception e) {   
  57.             throw new Exception(e);   
  58.         }   
  59.     }   
  60.   
  61.     /**  
  62.      *   
  63.      * @param is  
  64.      *            初始化xls文件的读取参数  
  65.      * @throws Exception  
  66.      */  
  67.   
  68.     public void read(InputStream is) throws Exception {   
  69.         try {   
  70.             // 创建xls工作表对象   
  71.             readBook = Workbook.getWorkbook(is);   
  72.             // 只读取第一个工作表中的内容   
  73.             sheet = readBook.getSheet(0);   
  74.             currIndex = 0;   
  75.             isFirst = true;   
  76.         } catch (Exception e) {   
  77.             throw new Exception(e);   
  78.         }   
  79.     }   
  80.   
  81.     /**  
  82.      * 读取一行xls文件中的数据  
  83.      *   
  84.      * @return 包含数据的String列表  
  85.      */  
  86.     public ArrayList<String> readLine() {   
  87.         alLineContent = new ArrayList<String>();   
  88.         int i = 0;   
  89.         String content = null;   
  90.         while (true) {   
  91.             if (!isFirst && i >= firstDataCount)   
  92.                 break;   
  93.             try {   
  94.                 // 读取一个单元格的数据   
  95.                 cell = sheet.getCell(i, currIndex);   
  96.                 i++;   
  97.             } catch (Exception e) {   
  98.                 // 没有数据可读取   
  99.                 if (i == 0)   
  100.                     return null;   
  101.                 // 读取首行   
  102.                 if (isFirst) {   
  103.                     firstDataCount = i;   
  104.                     isFirst = false;   
  105.                     break;   
  106.                 } else  
  107.                     content = "";   
  108.             }   
  109.             content = cell.getContents();   
  110.             // 首行存在空值时认为提取数据完毕   
  111.             if (isFirst && "".equals(content)) {   
  112.                 firstDataCount = i - 1;   
  113.                 isFirst = false;   
  114.                 break;   
  115.             }   
  116.             alLineContent.add(content);   
  117.         }   
  118.         currIndex++;   
  119.         return alLineContent;   
  120.     }   
  121.   
  122.     /**  
  123.      * 读取xls文件中的所有可读取数据  
  124.      */  
  125.     public ArrayList<ArrayList<String>> readAll() {   
  126.         ArrayList<ArrayList<String>> alAllData = new ArrayList<ArrayList<String>>();   
  127.         ArrayList<String> data = null;   
  128.         while (true) {   
  129.             data = this.readLine();   
  130.             if (data == null)   
  131.                 break;   
  132.             alAllData.add(data);   
  133.         }   
  134.         return alAllData;   
  135.     }   
  136.   
  137.     public void closeRead() {   
  138.         readBook.close();   
  139.     }   
  140.   
  141.     /**  
  142.      * 创建一个xls文件并初始化写入参数  
  143.      *   
  144.      * @param filePath  
  145.      *            xls文件路径  
  146.      */  
  147.     public void write(String filePath) throws Exception {   
  148.         try {   
  149.             // 打开.xls文件   
  150.             writeBook = Workbook.createWorkbook(new File(filePath));   
  151.             // 创建一个工作表   
  152.             writeSheet = writeBook.createSheet("Sheet1"0);   
  153.             currIndex = 0;   
  154.         } catch (Exception e) {   
  155.             throw new Exception(e);   
  156.         }   
  157.     }   
  158.   
  159.     /**  
  160.      * 将一条数据写入xls文件中  
  161.      *   
  162.      * @param dataLine  
  163.      *            需要写入的数据集合  
  164.      */  
  165.     public void writeLine(ArrayList<String> dataLine) throws Exception {   
  166.         try {   
  167.             for (int i = 0; i < dataLine.size(); i++) {   
  168.                 label = new Label(i, currIndex, dataLine.get(i));   
  169.                 writeSheet.addCell(label);   
  170.             }   
  171.             currIndex++;   
  172.         } catch (Exception e) {   
  173.             throw new Exception(e);   
  174.         }   
  175.     }   
  176.   
  177.     /**  
  178.      * 将所有数据写入xls文件  
  179.      *   
  180.      * @param data需要写入的数据  
  181.      */  
  182.     public void writeAll(ArrayList<ArrayList<String>> data) throws Exception {   
  183.         for (int i = 0; i < data.size(); i++) {   
  184.             this.writeLine(data.get(i));   
  185.         }   
  186.     }   
  187.   
  188.     public void closeWrite() throws Exception {   
  189.         try {   
  190.             // 将值写到文件中   
  191.             writeBook.write();   
  192.             writeBook.close();   
  193.         } catch (Exception e) {   
  194.             throw new Exception(e);   
  195.         }   
  196.     }   
  197. }  
package com.pjb.sys.util;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * 提供对XLS格式类型的文件进行处理
 * 
 * @author Administrator
 * 
 */
public class XlsTools {
	private Workbook readBook;

	private int currIndex;

	private ArrayList<String> alLineContent;

	private Cell cell;

	private int firstDataCount;

	private boolean isFirst;

	private Sheet sheet;

	private WritableWorkbook writeBook;

	private WritableSheet writeSheet;

	private Label label;

	/**
	 * 初始化xls文件的读取参数
	 * 
	 * @param filePath
	 *            xls文件路径
	 * 
	 */
	public void read(String filePath) throws Exception {
		try {
			// 创建xls工作表对象
			readBook = Workbook.getWorkbook(new File(filePath));
			// 只读取第一个工作表中的内容
			sheet = readBook.getSheet(0);
			currIndex = 0;
			isFirst = true;
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	/**
	 * 
	 * @param is
	 *            初始化xls文件的读取参数
	 * @throws Exception
	 */

	public void read(InputStream is) throws Exception {
		try {
			// 创建xls工作表对象
			readBook = Workbook.getWorkbook(is);
			// 只读取第一个工作表中的内容
			sheet = readBook.getSheet(0);
			currIndex = 0;
			isFirst = true;
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	/**
	 * 读取一行xls文件中的数据
	 * 
	 * @return 包含数据的String列表
	 */
	public ArrayList<String> readLine() {
		alLineContent = new ArrayList<String>();
		int i = 0;
		String content = null;
		while (true) {
			if (!isFirst && i >= firstDataCount)
				break;
			try {
				// 读取一个单元格的数据
				cell = sheet.getCell(i, currIndex);
				i++;
			} catch (Exception e) {
				// 没有数据可读取
				if (i == 0)
					return null;
				// 读取首行
				if (isFirst) {
					firstDataCount = i;
					isFirst = false;
					break;
				} else
					content = "";
			}
			content = cell.getContents();
			// 首行存在空值时认为提取数据完毕
			if (isFirst && "".equals(content)) {
				firstDataCount = i - 1;
				isFirst = false;
				break;
			}
			alLineContent.add(content);
		}
		currIndex++;
		return alLineContent;
	}

	/**
	 * 读取xls文件中的所有可读取数据
	 */
	public ArrayList<ArrayList<String>> readAll() {
		ArrayList<ArrayList<String>> alAllData = new ArrayList<ArrayList<String>>();
		ArrayList<String> data = null;
		while (true) {
			data = this.readLine();
			if (data == null)
				break;
			alAllData.add(data);
		}
		return alAllData;
	}

	public void closeRead() {
		readBook.close();
	}

	/**
	 * 创建一个xls文件并初始化写入参数
	 * 
	 * @param filePath
	 *            xls文件路径
	 */
	public void write(String filePath) throws Exception {
		try {
			// 打开.xls文件
			writeBook = Workbook.createWorkbook(new File(filePath));
			// 创建一个工作表
			writeSheet = writeBook.createSheet("Sheet1", 0);
			currIndex = 0;
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	/**
	 * 将一条数据写入xls文件中
	 * 
	 * @param dataLine
	 *            需要写入的数据集合
	 */
	public void writeLine(ArrayList<String> dataLine) throws Exception {
		try {
			for (int i = 0; i < dataLine.size(); i++) {
				label = new Label(i, currIndex, dataLine.get(i));
				writeSheet.addCell(label);
			}
			currIndex++;
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	/**
	 * 将所有数据写入xls文件
	 * 
	 * @param data需要写入的数据
	 */
	public void writeAll(ArrayList<ArrayList<String>> data) throws Exception {
		for (int i = 0; i < data.size(); i++) {
			this.writeLine(data.get(i));
		}
	}

	public void closeWrite() throws Exception {
		try {
			// 将值写到文件中
			writeBook.write();
			writeBook.close();
		} catch (Exception e) {
			throw new Exception(e);
		}
	}
}

 

接下来,我们以Struts1.2的FormFile做文件上传。编写如下Form

 

Java代码 复制代码
  1. package com.pjb.struts.form;   
  2.   
  3. import org.apache.struts.action.ActionForm;   
  4. import org.apache.struts.upload.FormFile;   
  5.   
  6. @SuppressWarnings("serial")   
  7. public class UploadForm extends ActionForm {   
  8.   
  9.     private FormFile formFile;   
  10.   
  11.     public FormFile getFormFile() {   
  12.         return formFile;   
  13.     }   
  14.   
  15.     public void setFormFile(FormFile formFile) {   
  16.         this.formFile = formFile;   
  17.     }   
  18. }  
package com.pjb.struts.form;

import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

@SuppressWarnings("serial")
public class UploadForm extends ActionForm {

	private FormFile formFile;

	public FormFile getFormFile() {
		return formFile;
	}

	public void setFormFile(FormFile formFile) {
		this.formFile = formFile;
	}
}

 

 

 JSP页面

Java代码 复制代码
  1. <%@ page language="java" contentType="text/html; charset=utf-8"%>   
  2. <%@ include file="/page/importTag.jsp"%>   
  3. <html>   
  4.     <head>   
  5.         <%   
  6.             String str = "<script type='text/javascript'>" + "\n alert('操作成功');" + "\n</script>";   
  7.             String reuslt = (String) request.getAttribute("result");   
  8.             if ("1".equals(reuslt))   
  9.                 out.println(str);   
  10.         %>   
  11.     </head>   
  12.     <body>   
  13.         <div align="center">   
  14.             <html:form action="/ExcelImport.do?method=upload" method="post" enctype="multipart/form-data">   
  15.                 选择导入文件<html:file property="formFile" onkeydown="javascrpit:return false;" />   
  16.                 <input type="submit" value="导入数据" />   
  17.             </html:form>   
  18.         </div>   
  19.     </body>   
  20. </html>  
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ include file="/page/importTag.jsp"%>
<html>
	<head>
		<%
			String str = "<script type='text/javascript'>" + "\n alert('操作成功');" + "\n</script>";
			String reuslt = (String) request.getAttribute("result");
			if ("1".equals(reuslt))
				out.println(str);
		%>
	</head>
	<body>
		<div align="center">
			<html:form action="/ExcelImport.do?method=upload" method="post" enctype="multipart/form-data">
				选择导入文件<html:file property="formFile" onkeydown="javascrpit:return false;" />
				<input type="submit" value="导入数据" />
			</html:form>
		</div>
	</body>
</html>

 

 

Struts Action代码如下。

 

Java代码 复制代码
  1. /**  
  2.  * 读XLS数据  
  3.  *   
  4.  * @param mapping  
  5.  * @param form  
  6.  * @param request  
  7.  * @param response  
  8.  * @return ActionForward  
  9.  * @throws Exception  
  10.  */  
  11. public ActionForward readXls(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)   
  12.         throws Exception {   
  13.     try {   
  14.         UploadForm uploadForm = (UploadForm) form;   
  15.         FormFile file = uploadForm.getFormFile();   
  16.         InputStream is = file.getInputStream();   
  17.         XlsTools xlsTools = new XlsTools();   
  18.         xlsTools.read(is);   
  19.         //读Xls行所有数据并封装   
  20.         ArrayList<ArrayList<String>> listAll = xlsTools.readAll();   
  21.         xlsTools.closeRead();   
  22.         List<UserBean> userList = new ArrayList<UserBean>();   
  23.         for (int i = 1; i < listAll.size(); i++) {   
  24.             ArrayList<String> aList = listAll.get(i);   
  25.             UserBean user = new UserBean();   
  26.             user.setUserName(aList.get(0));   
  27.             userList.add(user);   
  28.         }   
  29.         logger.info(userList);   
  30.         //调用Service写入数据库......   
  31.         request.setAttribute("result""1");   
  32.         return mapping.getInputForward();   
  33.     } catch (Exception e) {   
  34.         e.printStackTrace();   
  35.         logger.error(e.getMessage());   
  36.         request.setAttribute("errMsg", e.getMessage());   
  37.     }   
  38.     return mapping.findForward("error");   
  39.   
  40. }  
	/**
	 * 读XLS数据
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws Exception
	 */
	public ActionForward readXls(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			UploadForm uploadForm = (UploadForm) form;
			FormFile file = uploadForm.getFormFile();
			InputStream is = file.getInputStream();
			XlsTools xlsTools = new XlsTools();
			xlsTools.read(is);
			//读Xls行所有数据并封装
			ArrayList<ArrayList<String>> listAll = xlsTools.readAll();
			xlsTools.closeRead();
			List<UserBean> userList = new ArrayList<UserBean>();
			for (int i = 1; i < listAll.size(); i++) {
				ArrayList<String> aList = listAll.get(i);
				UserBean user = new UserBean();
				user.setUserName(aList.get(0));
				userList.add(user);
			}
			logger.info(userList);
			//调用Service写入数据库......
			request.setAttribute("result", "1");
			return mapping.getInputForward();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			request.setAttribute("errMsg", e.getMessage());
		}
		return mapping.findForward("error");

	}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics