Jxl读写Excel文件

        最近要使用Excel文件的导入导出,比较了一下Jxl和poi两种方式,Jxl相对简单,但是不支持xlsx格式的(2003之上版本的),下面先写一下Jxl的demo。无论是那方式,将Excel分为 Workbook(代表Excel的整个工作空间),Sheet(代表Workbook的每一个Sheet页),Row(代表Sheet中的每一行),Cell(代表Row中的每一个块元素)。

一、使用到的包

       首先需要导入jxl-2.6.12.jar包。Maven坐标为:

       

 <dependency>
			<groupId>net.sourceforge.jexcelapi</groupId>
			<artifactId>jxl</artifactId>
			<version>2.6.12</version>
		</dependency>


二、Jxl的读写Demo

    

package org.andy.excel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

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

import org.junit.Test;

public class JxlExcelTest {

	public static void readExcel(String filePath) {
		if (null != filePath && !"".equals(filePath.trim())) {
			Workbook workbook = null;
			InputStream inputStream = null;
			try {
				inputStream = new FileInputStream(filePath);
				workbook = Workbook.getWorkbook(inputStream);
				if (null == workbook) {
					return;
				}
				//获取第一个sheet
				Sheet sheet = workbook.getSheet(0);

				if (null == sheet) {
					return;
				}
				// 获取所有的行
				for (int i = 0; i < sheet.getRows(); i++) {
					// 得到当前行的所有单元格
					Cell[] cells = sheet.getRow(i);
					for (Cell cell : cells) {
						System.out.println(cell.getContents());
					}

				}
				
				workbook.close();

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (null != inputStream) {
					try {
						inputStream.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

	}

	public void writeExcel(String filePath) {

		if (null != filePath && !"".equals(filePath.trim())) {

			WritableWorkbook wWorkbook = null;
			OutputStream outputStream = null;

			// 根据不同的excel格式创建workbook
			if (filePath.trim().toLowerCase().endsWith(".xls")) {

				try {
					outputStream = new FileOutputStream(filePath);
					wWorkbook = Workbook.createWorkbook(outputStream);
					WritableSheet wSheet = wWorkbook.createSheet("sheet0", 0);
					// 添加string
					Label label = new Label(0, 0, "andy string");
					wSheet.addCell(label);
					//需要write
					wWorkbook.write();
					
					wWorkbook.close();
					
				} catch (Exception e) {
					e.printStackTrace();
				} finally {

					if (null != outputStream) {
						try {
							outputStream.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

				}

			}

		}
	}

	@Test
	public void read() {
		readExcel("C:\\andy1.xls");
	}

	@Test
	public void write() {
		writeExcel("C:\\andy1.xls");
	}
}

    

你可能感兴趣的:(poi,JXL,Excel读写)