最近要使用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");
}
}